Javascript: the important bits
-
Upload
chris-saylor -
Category
Technology
-
view
731 -
download
0
Transcript of Javascript: the important bits
JAVASCRIPT: THEJAVASCRIPT: THEIMPORTANT BITSIMPORTANT BITS
REVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS AREVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS ABRIEF INTRO TO NODEJSBRIEF INTRO TO NODEJS
THINK YOU KNOW JAVASCRIPT?THINK YOU KNOW JAVASCRIPT?typeof [] === "array"; false0.1 + 0.2 === 0.3; falsea === null; false0 == '0'; true1 == '1'; true'' == '0'; false'' == 0; true'false' == false; false
True or false?
THINK YOU KNOW JAVASCRIPT?THINK YOU KNOW JAVASCRIPT?
What does this return?
return{ a: "hello"}
THINK YOU KNOW JAVASCRIPT?THINK YOU KNOW JAVASCRIPT?
LET'S GET STARTED WITH THE BASICS.LET'S GET STARTED WITH THE BASICS.
VARIABLESVARIABLESWhen declairing a variable without the "var", it puts the variable in
global space which can be problematic.
function hello() { test1 = 'hello'; // global scope var test2 = 'hello2'; // this function scope}
hello();
console.log(test1); // 'hello';console.log(test2); // undefined
SCOPINGSCOPINGThere is no block scoping, only function scoping:
If you want to block the scope of the above loop:
for (var i = 0; i < 10; i++) { console.log(i);}console.log(i); // prints 10
(function () { for (var i = 0; i < 10; i++) { console.log(i); }}());var i;console.log(i); // undefined
SCOPE IN CALLBACKSSCOPE IN CALLBACKSIn callbacks, you can share variables from the parent function:
var obj = { objValue: 'hello', test: function() { var self = this; setTimeout(function() { console.log(this.objValue); // undefined console.log(self.objValue); // 'hello' }, 10); }}
OBJECTS AND "CLASSES"OBJECTS AND "CLASSES"Objects are like JSON with some class aspects known as
prototypes.
OBJECTS AND "CLASSES"OBJECTS AND "CLASSES"An example class:
Animal = (function() {
function Animal(name) { this.name = name; }
Animal.prototype.move = function() { return alert(this.name + ' moved.'); };
return Animal;
}());
COMMON JAVASCRIPT PATTERNSCOMMON JAVASCRIPT PATTERNS
IMMEDIATE EXECUTION FUNCTIONIMMEDIATE EXECUTION FUNCTION
This immediately executes your logic as anonymous scope.
(function() { // Your logic here}());
PRIVATE PATTERNPRIVATE PATTERN
This pattern allows you to expose only what you want exposed.
var getCount = function() { var count = 0; return function() { return ++count; }}var next = getCount();console.log(next()); // 1console.log(next()); // 2
INITIALIZATIONINITIALIZATIONVariable initialization:
Complex object initialization:
var value = value || 'somevalue';
({ val1: 1, val2: null, init: function() { this.val2 = 2; return this; }}).init();
LET'S GO OVER JQUERY OPTIMIZATION.LET'S GO OVER JQUERY OPTIMIZATION.
SELECTOR CACHINGSELECTOR CACHINGBad:
Good:
$('.someclass').text('replace some text.');$('.someclass').css('color', 'red');$('.someclass').focus();
$('.someclass') .text('replace some text.') .css('color', 'red') .focus();
SELECTOR CACHINGSELECTOR CACHINGCaching with callbacks.
Caching "this":
var $someotherclass = $('.someotherclass');$('.someclass').on('click', function(e) { $someotherclass.text('some event');});
$('.someclass').on('click', function(e)) { $this = $(this); $this.text('something'); $this.hide();});
EVENT ATTACHINGEVENT ATTACHINGWhen attaching events, use the "on" function.
What about dynamically generated links?
$('a').on('click', function(e)) { console.log('A link was clicked.');});
$(document).on('click', 'a', function(e)) { console.log('A link was clicked.');});
PROPERLY STOPPING EVENTSPROPERLY STOPPING EVENTSReturning false is not always a good thing:
$('a').on('click', function(e) { console.log('Stopping propagation.'); return false; // Same as: // e.preventDefault(); // e.stopPropagation();});$('a').on('click', function(e)) { console.log('Another click.'); // Never gets called because of the // return false in the above event.});
BASIC JQUERY PLUGIN STRUCTUREBASIC JQUERY PLUGIN STRUCTURE
Usage:
(function($) { $.fn.myLog = function() { return this.each(function() { console.log($(this)); }); }}(jQuery));
$('p').myLog();
INTRODUCTION TO NODEJSINTRODUCTION TO NODEJS
Nodejs is an event-driven language built on Google's V8 (in c).
It's package manager is known as and is now packaged withnodejs.
npm
NODEJS: HELLO WORLDNODEJS: HELLO WORLD
Source:
var http = require('http');http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n');}).listen(1337);console.log('Server running on port 1337');
http://nodejs.org/about/
NODEJS: DEPENDANCY MANAGEMENTNODEJS: DEPENDANCY MANAGEMENTYou can manage dependencies for your nodejs app in package.json:
This allows us to install our project dependencies with npm:
{ "name": "sample-app", "version": "0.0.1", "dependencies": { "express": "2.5.x" }}
npm install
NODEJS: EXPRESS SERVERNODEJS: EXPRESS SERVEROur hello world example in express:
var express = require('express');app = express.createServer()app.get('/', function(req, res) { res.send('Hello World');});app.listen(1337);console.log('Listening on port 1337');
NODEJS: CONNECT MIDDLEWARENODEJS: CONNECT MIDDLEWARERouting middleware is anything that implements the request,
response, and next function pattern.
Using this middleware:
// Request loggerfunction logger(req, res, next) { console.log("Path requested: " + req.path); next();}
app.get('/', logger, function(req, res) { res.send('Hello World');});
QUESTIONS?QUESTIONS?