Javascript: the important bits

29
JAVASCRIPT: THE JAVASCRIPT: THE IMPORTANT BITS IMPORTANT BITS REVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS A REVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS A BRIEF INTRO TO NODEJS BRIEF INTRO TO NODEJS

Transcript of Javascript: the important bits

Page 1: 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

Page 2: Javascript: the important bits

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?

Page 3: Javascript: the important bits

THINK YOU KNOW JAVASCRIPT?THINK YOU KNOW JAVASCRIPT?

What does this return?

return{ a: "hello"}

Page 4: Javascript: the important bits

THINK YOU KNOW JAVASCRIPT?THINK YOU KNOW JAVASCRIPT?

Page 5: Javascript: the important bits
Page 6: Javascript: the important bits

LET'S GET STARTED WITH THE BASICS.LET'S GET STARTED WITH THE BASICS.

Page 7: Javascript: the important bits

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

Page 8: Javascript: the important bits

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

Page 9: Javascript: the important bits

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); }}

Page 10: Javascript: the important bits

OBJECTS AND "CLASSES"OBJECTS AND "CLASSES"Objects are like JSON with some class aspects known as

prototypes.

Page 11: Javascript: the important bits

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;

}());

Page 12: Javascript: the important bits

COMMON JAVASCRIPT PATTERNSCOMMON JAVASCRIPT PATTERNS

Page 13: Javascript: the important bits

IMMEDIATE EXECUTION FUNCTIONIMMEDIATE EXECUTION FUNCTION

This immediately executes your logic as anonymous scope.

(function() { // Your logic here}());

Page 14: Javascript: the important bits

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

Page 15: Javascript: the important bits

INITIALIZATIONINITIALIZATIONVariable initialization:

Complex object initialization:

var value = value || 'somevalue';

({ val1: 1, val2: null, init: function() { this.val2 = 2; return this; }}).init();

Page 16: Javascript: the important bits

LET'S GO OVER JQUERY OPTIMIZATION.LET'S GO OVER JQUERY OPTIMIZATION.

Page 17: Javascript: the important bits

SELECTOR CACHINGSELECTOR CACHINGBad:

Good:

$('.someclass').text('replace some text.');$('.someclass').css('color', 'red');$('.someclass').focus();

$('.someclass') .text('replace some text.') .css('color', 'red') .focus();

Page 18: Javascript: the important bits

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();});

Page 19: Javascript: the important bits

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.');});

Page 20: Javascript: the important bits

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.});

Page 21: Javascript: the important bits

BASIC JQUERY PLUGIN STRUCTUREBASIC JQUERY PLUGIN STRUCTURE

Usage:

(function($) { $.fn.myLog = function() { return this.each(function() { console.log($(this)); }); }}(jQuery));

$('p').myLog();

Page 22: Javascript: the important bits

INTRODUCTION TO NODEJSINTRODUCTION TO NODEJS

Page 23: Javascript: the important bits

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

Page 24: Javascript: the important bits

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/

Page 25: Javascript: the important bits

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

Page 26: Javascript: the important bits

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');

Page 27: Javascript: the important bits

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');});

Page 28: Javascript: the important bits

QUESTIONS?QUESTIONS?

Page 29: Javascript: the important bits