Wednesday, June 29, 2011

Dom Node is Unique

Here is an interesting fact about DOM nodes. When you are moving a node from one parent to another parent, you don't have to remove it from first parent. Yes! you read it right. You don't have to remove it from first parent secondParent.appendChild(domNode) will do the needful. Since DOM nodes are unique, they can be there only at one place at a time.

Monday, February 21, 2011

ProToVis: SVG Based Data Visualization Library

Just went through one of most advanced data visualization library using JavaScript. Library looks promising and very well documented. Even though there is no clear list of browsers supported you should assume this work only in modern browsers, and will make a strong case of in-house products.

This site promotes learn by example, and examples cover almost all possible data visualization needs. For most generic needs just copy-paste example should do.

http://vis.stanford.edu/protovis/

Friday, December 31, 2010

Private Properties and Methods:

Javascript has no special syntax to denote private properties or methods. But the same effect can be achieved declaring variables or methods with keyword "var" in function or object scope. Below is an example concentrate on this concept:


// In MyObject all properties and methods are public, as there is no use of "var" inside object
function MyObject() {
   this.name = "Ravi Kumar";
   this.getName = function() {
      console.log(this.name) }
   }
var myObj = new MyObject()
myObj.getName() // Ravi Kumar
console.log(myObj.name) // Ravi Kumar


//Adding var will make name public
function MyObject() {
   var name = "Ravi Kumar";
   this.getName = function() {
      console.log(name) }
   }
var myObj = new MyObject()
myObj.getName() // Ravi Kumar
console.log(myObj.name) // undefined

Where as while returning private members of type Object or Array, you should note that, when we pass Objects or Array we pass it by reference. Hence while returning private Objects and Arrays we would be exposing them to further altercations. So for being on the safer side, while returning general utility for clone/copy should be used, with that whatever we return will not have any relation with the Private member.

Privileged Methods: Privileged Methods is nothing but method created in local scope of variables which has access to those variables. In above example getName is a privileged method. 

If you want to declare private members using object literal you should wrap it with immediate function as follows.


var myObj=(function(){
    var name="Ravi Kumar";
    return {
        getName:function(){
            return name;
        }
    }
}())

myObj.getName() // Ravi Kumar

Wednesday, December 29, 2010

Some More Patterns

Init-Time Branching: Minimizing computing as far as possible. For example browser features doesn't change over a session. Instead of checking browser features every time it's better to compute them once and according to that, update other utility function


Memoization: If return value of a function never change for given inputs, it's better to cache them in function as hashtable of serialized input params and outputs. Since functions are objects they can have there own properties and methods.


Configuration Object: It's better to use single object parameter against, multiple input parameters. As project grows, the requirement grows and number of input parameters grows. It's not a good idea to send too many parameters to a function, it's hard to maintain as well. Hence we can send an object which has key value pairs of input names and parameters, so that it's easy to add or remove parameters. Also we can skip optional parameters easily.


Currying: Partial Apply. We can transform an existing function to return another function when it has less number of parameters, and hardcode sent parameter so that we don't have to send that again. Here is an example:



var multiply=function(a,b){
    var olda=a, oldb=b;
    if(oldb===undefined){
        return function(newb){
            return olda*newb;
        }
    }
}


var multiplyby3 = multiply(3)
multiplyby3(4) //12 


var multiplyby9 = multiply(9)
multiplyby9(4) //36

Immediate Object Initialization

Just like Immediate functions we can declare immediate object initializations as well. 


Example:

({
init:function(){
    console.log('immediate initialization')
}
}).init()

Only problem with this is, most of the minification tools fail to minify such object declarations. 

Tuesday, December 28, 2010

Immediate Functions

Immediate Functions are the function which gets executed as soon as it's defined. For Example:

(function () { 

alert('Im an immediate function');

}());


or

(function () { 

alert('Im an immediate function');

})();


Only difference between above 2 examples is placement of "()", both are valid but JSLint prefers first one.Observe extra parenthesis after function definition and another set of parenthesis covering whole thing. First set of parenthesis after function definition make sure function executed immediately, and second set of parenthesis is needed only when you are not assigning it to an variable name. if you are assigning it to a variable you can omit them, like

var boo = function () { 

return 'Im an immediate function';

}()


Here function gets executed immediately and assigns returning value to a variable "boo".  When you have some server side code returning some data which needs to be kept private from further alterations, we can wrap them in immediate function, and expose only needed part of it by providing methods to do so.

Lazy Function Definition

Lazy Function Definition is a pattern of function definition where a function is not defined properly until you execute it for first time. Assume you have some setup work which you need to do on page load, and you have to do that only once. In such case you can overwrite your function while executing it for first time. 

For example:
Assume that you need a function to return page loaded time, you write a function that get called on page load, and every time you need to refer page loaded time.

var getPageLoadedTime =function (){

var pageLoadedTime = new Date();

getPageLoadedTime=function(){

return pageLoadedTime;

}

}


When you call this function first time, it will set and store pageLoadedTime, and overwrite old function with new one that return the same time on every subsequent calls. This can be very useful when you have to do lot of setting up in your code. Also it can help you in reducing global parameters.