KEMBAR78
Javascript: the important bits | PDF
JAVASCRIPT: THE
         IMPORTANT BITS
REVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS A
                   BRIEF INTRO TO NODEJS
THINK YOU KNOW JAVASCRIPT?
     typeof [] === "array"; false
     0.1 + 0.2 === 0.3; false
     a === null; false
     0 == '0'; true
     1 == '1'; true
     '' == '0'; false
     '' == 0; true
     'false' == false; false

          True or false?
THINK YOU KNOW JAVASCRIPT?
return
{
  a: "hello"
}



                What does this return?
THINK YOU KNOW JAVASCRIPT?
LET'S GET STARTED WITH THE BASICS.
VARIABLES
When 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
SCOPING
       There is no block scoping, only function scoping:
for (var i = 0; i < 10; i++) {
  console.log(i);
}
console.log(i); // prints 10



       If you want to block the scope of the above loop:
(function () {
  for (var i = 0; i < 10; i++) {
    console.log(i);
  }
}());
var i;
console.log(i); // undefined
SCOPE IN CALLBACKS
In 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 are like JSON with some class aspects known as
                      prototypes.
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 PATTERNS
IMMEDIATE EXECUTION FUNCTION
(function() {
  // Your logic here
}());



This immediately executes your logic as anonymous scope.
PRIVATE PATTERN
 var getCount = function() {
   var count = 0;
   return function() {
       return ++count;
   }
 }
 var next = getCount();
 console.log(next()); // 1
 console.log(next()); // 2



This pattern allows you to expose only what you want exposed.
INITIALIZATION
                        Variable initialization:
var value = value || 'somevalue';



                   Complex object initialization:
({
  val1: 1,
  val2: null,
  init: function() {
    this.val2 = 2;
    return this;
  }
}).init();
LET'S GO OVER JQUERY OPTIMIZATION.
SELECTOR CACHING
                                    Bad:
$('.someclass').text('replace some text.');
$('.someclass').css('color', 'red');
$('.someclass').focus();



                                   Good:
$('.someclass')
  .text('replace some text.')
  .css('color', 'red')
  .focus();
SELECTOR CACHING
                       Caching with callbacks.
var $someotherclass = $('.someotherclass');
$('.someclass').on('click', function(e) {
  $someotherclass.text('some event');
});



                             Caching "this":
$('.someclass').on('click', function(e)) {
  $this = $(this);
  $this.text('something');
  $this.hide();
});
EVENT ATTACHING
        When attaching events, use the "on" function.
$('a').on('click', function(e)) {
  console.log('A link was clicked.');
});



           What about dynamically generated links?
$(document).on('click', 'a', function(e)) {
  console.log('A link was clicked.');
});
PROPERLY STOPPING EVENTS
           Returning 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 STRUCTURE
(function($) {
  $.fn.myLog = function() {
        return this.each(function() {
                console.log($(this));
        });
  }
}(jQuery));



                                  Usage:
$('p').myLog();
INTRODUCTION TO NODEJS
Nodejs is an event-driven language built on Google's V8 (in c).

It's package manager is known as npm and is now packaged with
                            nodejs.
NODEJS: HELLO WORLD
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Worldn');
}).listen(1337);
console.log('Server running on port 1337');


                        Source:   http://nodejs.org/about/
NODEJS: DEPENDANCY MANAGEMENT
You can manage dependencies for your nodejs app in package.json:
   {
       "name": "sample-app",
       "version": "0.0.1",
       "dependencies": {
         "express": "2.5.x"
       }
   }




   This allows us to install our project dependencies with npm:
   npm install
NODEJS: EXPRESS SERVER
               Our 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 MIDDLEWARE
Routing middleware is anything that implements the request,
           response, and next function pattern.
// Request logger
function logger(req, res, next) {
  console.log("Path requested: " + req.path);
  next();
}




                        Using this middleware:
app.get('/', logger, function(req, res) {
  res.send('Hello World');
});
QUESTIONS?
Javascript: the important bits

Javascript: the important bits

  • 1.
    JAVASCRIPT: THE IMPORTANT BITS REVIEWING JAVASCRIPT AND JQUERY FUNDAMENTALS AS WELL AS A BRIEF INTRO TO NODEJS
  • 2.
    THINK YOU KNOWJAVASCRIPT? typeof [] === "array"; false 0.1 + 0.2 === 0.3; false a === null; false 0 == '0'; true 1 == '1'; true '' == '0'; false '' == 0; true 'false' == false; false True or false?
  • 3.
    THINK YOU KNOWJAVASCRIPT? return { a: "hello" } What does this return?
  • 4.
    THINK YOU KNOWJAVASCRIPT?
  • 6.
    LET'S GET STARTEDWITH THE BASICS.
  • 7.
    VARIABLES When declairing avariable 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
  • 8.
    SCOPING There is no block scoping, only function scoping: for (var i = 0; i < 10; i++) { console.log(i); } console.log(i); // prints 10 If you want to block the scope of the above loop: (function () { for (var i = 0; i < 10; i++) { console.log(i); } }()); var i; console.log(i); // undefined
  • 9.
    SCOPE IN CALLBACKS Incallbacks, 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); } }
  • 10.
    OBJECTS AND "CLASSES" Objectsare like JSON with some class aspects known as prototypes.
  • 11.
    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; }());
  • 12.
  • 13.
    IMMEDIATE EXECUTION FUNCTION (function(){ // Your logic here }()); This immediately executes your logic as anonymous scope.
  • 14.
    PRIVATE PATTERN vargetCount = function() { var count = 0; return function() { return ++count; } } var next = getCount(); console.log(next()); // 1 console.log(next()); // 2 This pattern allows you to expose only what you want exposed.
  • 15.
    INITIALIZATION Variable initialization: var value = value || 'somevalue'; Complex object initialization: ({ val1: 1, val2: null, init: function() { this.val2 = 2; return this; } }).init();
  • 16.
    LET'S GO OVERJQUERY OPTIMIZATION.
  • 17.
    SELECTOR CACHING Bad: $('.someclass').text('replace some text.'); $('.someclass').css('color', 'red'); $('.someclass').focus(); Good: $('.someclass') .text('replace some text.') .css('color', 'red') .focus();
  • 18.
    SELECTOR CACHING Caching with callbacks. var $someotherclass = $('.someotherclass'); $('.someclass').on('click', function(e) { $someotherclass.text('some event'); }); Caching "this": $('.someclass').on('click', function(e)) { $this = $(this); $this.text('something'); $this.hide(); });
  • 19.
    EVENT ATTACHING When attaching events, use the "on" function. $('a').on('click', function(e)) { console.log('A link was clicked.'); }); What about dynamically generated links? $(document).on('click', 'a', function(e)) { console.log('A link was clicked.'); });
  • 20.
    PROPERLY STOPPING EVENTS Returning 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. });
  • 21.
    BASIC JQUERY PLUGINSTRUCTURE (function($) { $.fn.myLog = function() { return this.each(function() { console.log($(this)); }); } }(jQuery)); Usage: $('p').myLog();
  • 22.
  • 23.
    Nodejs is anevent-driven language built on Google's V8 (in c). It's package manager is known as npm and is now packaged with nodejs.
  • 24.
    NODEJS: HELLO WORLD varhttp = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337); console.log('Server running on port 1337'); Source: http://nodejs.org/about/
  • 25.
    NODEJS: DEPENDANCY MANAGEMENT Youcan manage dependencies for your nodejs app in package.json: { "name": "sample-app", "version": "0.0.1", "dependencies": { "express": "2.5.x" } } This allows us to install our project dependencies with npm: npm install
  • 26.
    NODEJS: EXPRESS SERVER Our 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');
  • 27.
    NODEJS: CONNECT MIDDLEWARE Routingmiddleware is anything that implements the request, response, and next function pattern. // Request logger function logger(req, res, next) { console.log("Path requested: " + req.path); next(); } Using this middleware: app.get('/', logger, function(req, res) { res.send('Hello World'); });
  • 28.