Wednesday, March 16, 2016

Async patterns in javascript

Generators (Yield) 

The generator will pause itself and the iterator will resume it.  It can start and stop infinite number of time.

function* gen(){
    console.log("Hello");
    //The function will resume itself waiting for the next iterator
    yield null;
    console.log("World");
}

var it=gen();
it.next();   //prints "Hello"
it.next();   //print  "World"










Saturday, March 12, 2016

Create a widget using javascript

Javascript code

function Widget(width,height){
    this.width=width||50;
    this.height=height||50;
    this.$elem=null;
}

Widget.prototype.render=function($where){
    if(this.$elem){
        this.$elem.css({
            width:this.width+"px",
            height:this.height+"px"
        }).appendTo($where);
    }
};

function Button(width,height,label){
    Widget.call(this,width,height);
    this.label=label;
    this.$elem=$("<button>").text(this.label);
}

Button.prototype.render=function($where){
    Widget.prototype.render.call(this,$where);
    this.$elem.bind("click",this.onClick.bind(this));
};

Button.prototype.onClick=function(event){
    //We used this here because we use the hard binding in render function
    console.log("Button '"+ this.label+"' Was clicked");
};

$(document).ready(function(){
    var $body=$(document.body);
    var btn1=new Button(100,50,'Hola');
    var btn2= new Button(200,50,'Hello');

    btn1.render($body);
    btn2.render($body);
});


Equivalent javascript code

var Widget ={
    init: function(width,height){
        this.width=width||50;
        this.height=height||50;
        this.$elem=null;
    },
    insert: function($where){
        if(this.$elem){
            this.$elem.css({
                width:this.width+"px",
                height:this.height+"px"
            }).appendTo($where);
        }
    }
};

var Button =Object.create(Widget);

Button.setup=function(width,height,label){
    this.init(width,height);
    this.label=label||"Default";
    this.$elem=$("<button>").text(this.label);
};

Button.build=function($where){
    this.insert($where);
    this.$elem.click(this.onClick.bind(this));
};

Button.onClick=function(){
    console.log("Button '"+ this.label+"' clicked!");
};

$(document).ready( function(){
    var $body=$(document.body);

    var btn1=Object.create(Button);
    btn1.setup(125,30,"Hello");

    var btn2=Object.create(Button);
    btn2.setup(150,60,"Hola");

    btn1.build($body);
    btn2.build($body);

});


Html code

<html>

<head>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="widget.js"></script>
</head>

<body>

</body>


</html>



Friday, March 11, 2016

OLOO: Object Linked to Other Object

I was watching a session by Kyle Simpson about the object inheritance in javascript and he introduced this term that he called OLOO. Where b1 delegates to Bar delegates to Foo as in the example below:

Code

var Foo={
A screenshot from Kyle Simpson slides


    init: function(who){
        this.me=who;
    },
    identify:function(){
        return "I am "+ this.me;
    }
};

var Bar=Object.create(Foo);

Bar.speak=function(){
   
    alert("Hello, "+this.identify() +".");
};

var b1=Object.create(Bar);
b1.init("b1");
b1.speak();








Equivalent complicated code -->


Wednesday, March 2, 2016

Module patterns in javascript


Classic module pattern




ar classicModulePattern=(function(){
   
    var greeting={text: "hi"};

    return {
        sayHi: function(){
            console.log(greeting.text);
        }
    }   

})();


Modified module pattern 

The good thing about this module is that you can update it, you can remove and add attributes while in the classic module you will not be able to update the returned object.

var modifiedModulePattern= (function(){
    var publicAPI={
        sayHi: function(){
            publicAPI.sayBye();
        },
        sayBye:function(){
            console.log('Bye');
        }

    };
    return publicAPI;
})();

modifiedModulePattern.sayHi();


this keyword rules in javascript

I wrote down these notes while watching one of Kyle Simpson workshops about javascript and would like to share them with Y'all :

"Every function, while executing, has a reference to its current execution context, called this. "

There are 4 rules of how this word gets bound in JavaScript: 

"1.Was the function called with 'new' ?
2.Was the function called with 'call' or apply specifying explicit 'this' ?
3. Was the function called via a containing/owning object (context)?
4. Default : global object  "



Rule 1: Default binding rule
When the call site is the default "plain" like in the lines, the function stands alone by itself. The default binding rule applies.

function foo(){
    console.log(this.hi);
}

foo();   <---- function stands alone by itself.

If you are in strict mode, then default is undefined , otherwise define it in the global.


Rule 2: Implicit binding rule
It owns the content of the call site.

function foo(){
    console.log(this.hi);
}

var object1 ={hi:1984,func:foo};
var object2= {hi:2016,func:foo};

 object1.foo();  <---- //1984
object2.foo();   <---- //2016

Rule 3:

Explicit binding
If you use .call or .apply on the call side, They take their parameter as a this.

function sayHi(){
    console.log(this.hi);


var hi="Hola";
var object1={hi:"Hi"};

sayHi();                      <----- //Hola
sayHi.call(object1);    <----- //Hi

Hard binding 
Predictably reference the object that it has to reference.
function sayHi(){
      console.log(this.hi);
}


var object1 ={hi:"Hi"};
var object2 ={hi:"Hola"};


var orig=foo;
sayHi= function(){orig.call(object1)};


sayHi();                     <----- //Hi
sayHi.call(object2);   <----- //Hi



Rule 4: The new key word
There are 4 things happen when the new key word put in front of a function call 
1. A brand new object will be created 
2. That object gets linked to different object    <---- More  clarifications later
3. That object gets bound as this  key word
4.  If that object return nothing, It will implicitly returns this .









 
Example :
var object1={
      var name="Saif";
      printName:function(){
         console.log(name);
      }
}

var object2= {name:"Khaled", printName:object1.printName};

var name="Belal";
var printMe=object1.printMe; 

object1.printMe();    <---- Saif
object1.printMe();    <---- Khaled
printMe();                 <---- Belal



Tuesday, March 1, 2016

Hoisting in javascript

The variables deceleration will be moved to the top during the compilation phase and the variables in the screenshots below will not be printed as undefined.









While in the function example below, We will have undefined values.