JavaScript Module Pattern: In-Depth

0

Category :

The module pattern is a common JavaScript coding pattern. It's generally well understood, but there are a number of advanced uses that have not gotten a lot of attention.

The Basics

We'll start out with a simple overview of the module pattern

Anonymous Closures

This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We'll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.

(function () { 
    // ... all vars and functions are in this scope only 
    // still maintains access to all globals 
}());

Notice the () around the anonymous function. This is required by the language, since statements that begin with the token function are always considered to be function declarations. Including () creates a function expression instead.

Global Import

JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name. If none is found, that variable is assumed to be global. If it's used in an assignment, the global is created if it doesn't already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it's not obvious (to humans) which variables are global in a given file.

Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals.

(function ($, YAHOO) { 
    // now have access to globals jQuery (as $) and YAHOO in this code 
}(jQuery, YAHOO));

Module Export

Sometimes you don't just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function's return value. Doing so will complete the basic module pattern, so here's a complete example:

var MODULE = (function () { 
    var my = {}, 
        privateVariable = 1; 
     
    function privateMethod() { 
        // ... 
    } 
     
    my.moduleProperty = 1; 
    my.moduleMethod = function () { 
        // ... 
    }; 
     
    return my; 
}());

Notice that we've declared a global module named MODULE, with two public properties: a method named MODULE.moduleMethod and a variable named MODULE.moduleProperty. In addition, it maintains private internal state using the closure of the anonymous function.

Advanced Patterns

While the above is enough for many uses, we can take this pattern farther and create some very powerful, extensible constructs. Lets work through them one-by-one, continuing with our module named MODULE.

Augmentation

One limitation of the module pattern so far is that the entire module must be in one file. Anyone who has worked in a large code-base understands the value of splitting among multiple files. Luckily, we have a nice solution to augment modules. First, we import the module, then we add properties, then we export it. Here's an example, augmenting our MODULE from above:

var MODULE = (function (my) { 
    my.anotherMethod = function () { 
        // added method... 
    }; 
 
    return my; 
}(MODULE));

After this code has run, our module will have gained a new public method named MODULE.anotherMethod. This augmentation file will also maintain its own private internal state and imports.

Loose Augmentation

While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn't always necessary. One of the best things a JavaScript application can do for performance is to load scripts asynchronously. We can create flexible multi-part modules that can load themselves in any order with loose augmentation. Each file should have the following structure:

var MODULE = (function (my) { 
    // add capabilities... 
     
    return my; 
}(MODULE || {}));

In this pattern, the var statement is always necessary. Note that the import will create the module if it does not already exist. This means you can use a tool like LABjs and load all of your module files in parallel, without needing to block.

Tight Augmentation

While loose augmentation is great, it does place some limitations on your module. Most importantly, you cannot override module properties safely. You also cannot use module properties from other files during initialization (but you can at run-time after intialization). Tight augmentation implies a set loading order, but allows overrides. Here is a simple example (augmenting our original MODULE):

var MODULE = (function (my) { 
    var old_moduleMethod = my.moduleMethod; 
     
    my.moduleMethod = function () { 
        // method override, has access to old through old_moduleMethod... 
    }; 
     
    return my; 
}(MODULE));

Here we've overridden MODULE.moduleMethod, but maintain a reference to the original method, if needed.

Cloning and Inheritance


var MODULE_TWO = (function (old) { 
    var my = {}, 
        key; 
     
    for (key in old) { 
        if (old.hasOwnProperty(key)) { 
            my[key] = old[key]; 
        } 
    } 
     
    var super_moduleMethod = old.moduleMethod; 
    my.moduleMethod = function () { 
        // override method on the clone, access to super through super_moduleMethod 
    }; 
     
    return my; 
}(MODULE));

This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility. As I've written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references. Changing one will change the other. This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval. Nevertheless, I've included it for completeness.

Cross-File Private State

One severe limitation of splitting a module across multiple files is that each file maintains its own private state, and does not get access to the private state of the other files. This can be fixed. Here is an example of a loosely augmented module that will maintain private state across all augmentations:

var MODULE = (function (my) { 
    var _private = my._private = my._private || {}, 
        _seal = my._seal = my._seal || function () { 
            delete my._private; 
            delete my._seal; 
            delete my._unseal; 
        }, 
        _unseal = my._unseal = my._unseal || function () { 
            my._private = _private; 
            my._seal = _seal; 
            my._unseal = _unseal; 
        }; 
     
    // permanent access to _private, _seal, and _unseal 
     
    return my; 
}(MODULE || {}));

Any file can set properties on their local variable _private, and it will be immediately available to the others. Once this module has loaded completely, the application should call MODULE._seal(), which will prevent external access to the internal _private. If this module were to be augmented again, further in the application's lifetime, one of the internal methods, in any file, can call _unseal() before loading the new file, and call _seal() again after it has been executed.

Sub-modules

Our final advanced pattern is actually the simplest. There are many good cases for creating sub-modules. It is just like creating regular modules:

MODULE.sub = (function () { 
    var my = {}; 
    // ... 
     
    return my; 
}());

Sub-modules have all the advanced capabilities of normal modules, including augmentation and private state.

Conclusions

Most of the advanced patterns can be combined with each other to create more useful patterns. If I had to advocate a route to take in designing a complex application, I'd combine loose augmentation, private state, and sub-modules.

I haven't touched on performance here at all, but I'd like to put in one quick note: The module pattern is good for performance. It minifies really well, which makes downloading the code faster. Using loose augmentation allows easy non-blocking parallel downloads, which also speeds up download speeds. Initialization time is probably a bit slower than other methods, but worth the trade-off. Run-time performance should suffer no penalties so long as globals are imported correctly, and will probably gain speed in sub-modules by shortening the reference chain with local variables.

To close, here's an example of a sub-module that loads itself dynamically to its parent (creating it if it does not exist). I've left out private state for brevity, but including it would be simple. This code pattern allows an entire complex heirarchical code-base to be loaded completely in parallel with itself, sub-modules and all.

var UTIL = (function (parent, $) { 
    var my = parent.ajax = parent.ajax || {}; 
     
    my.get = function (url, params, callback) { 
        // ok, so I'm cheating a bit :) 
        return $.getJSON(url, params, callback); 
    }; 
     
    // etc... 
     
    return parent; 
}(UTIL || {}, jQuery));

my thanks to:
http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Javascript Closures

0

Category :

Douglas Crockford’s five part series on Javascript

Crockford shows a much nicer object creation strategy based on closures, which looks something like this:

var animalsApp = (function(){

    var new_animal = function(name) {
        var animal = {};

        animal.sayHello = function() {
            return "Hello, my name is " + name;
        }
        return animal;
    }

    var new_dog = function(name) {
        var dog = new_animal(name);

        dog.bark = function() {
            return "woof";
        }
        return dog;
    }

    var new_cat = function(name) {
        var cat = new_animal(name);

        cat.meow = function() {
            return "eeooowww";
        }
        return cat;
    }

    return {
        main: function(){
            var dog = new_dog("rover");

            console.log(dog.sayHello());
            console.log(dog.bark());

            var cat = new_cat("tom");

            console.log(cat.sayHello());
            console.log(cat.meow());
        }
    };
}());

animalsApp.main();

Using this technique we can create properly encapsulated objects. In the example above, our animalsApp only exposes a single function, main, new_animal, new_dog and new_cat are all private. The class definitions are very clear, any variables or functions defined in the constructor body are private and we only expose members that we explicitly attach to the object (dog.bark = function(){}).


my thanks to:
http://mikehadlow.blogspot.com/2010/12/javascript-defining-classes-with.html

Javascript Functions

0

Category :

Functions in JavaScript let you define code that is called on demand, instead of immediately. There are several ways to define a function:

Function Declaration

standard function statement
  • must always have an Identifier(function name).
  • parsed and evaluated before any other expressions are. Even if declaration is positioned last in a source, it will be evaluated before any other expressions contained in a scope.

function getarea(w,h){
 //standard function
 return w * h;
}

getarea(3,5) //calls function

Function Literal or Expression

an anonymous function assigned to a variable
var getarea = function(w,h){
 return w * h;
}

getarea(3,5) //calls function

Function Expression may omit Identifier.
Named Function Expressions may only access its Identifier in the scope of its newly-defined function
Named Function Expressions make for a much more pleasant debugging experience.

Function Constructor

creates a function on the fly, which is slower and generally discouraged
//syntax: new Function(argument1, argument2, ..., argumentY, functionbody) 
//all parameters must be a string

var getarea=new Function("w", "h", "var area=w*h; return area")
getarea(3,5) //calls function



What's the difference between declaration and expression?

The 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }
Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }

alert(typeof(test2)); //alerts 'undefined', surprise! 

test1(); //alerts 'function' because test2 is a function.

ECMAScript differentiates between two based on a context. If a function foo(){} is part of, say, assignment expression, it is considered a function expression. If, on the other hand, function foo(){} is contained in a function body or in a (top level of) program itself — it is parsed as a function declaration.

// declaration, since it's part of a Program
function foo(){};

// expression, since it's part of an AssignmentExpression
var bar = function foo(){};

// expression, since it's part of a NewExpression
new function bar(){};

(function(){
  function bar(){} // declaration, since it's part of a FunctionBody
})();

A somewhat less obvious example of function expression is the one where function is wrapped with parenthesis — (function foo(){}). The reason it is an expression is again due to a context: "(" and ")" constitute a grouping operator and grouping operator can only contain an expression

function foo(){} // function declaration
(function foo(){}); // function expression: due to grouping operator
  
try {
  // grouping operator can only contain expression, 
  //not a statement (which `var` is)
  (var x = 5); 
} catch(err) {
  // SyntaxError
}

Immediately-Invoked Function Expression (IIFE)

The most widely accepted way to tell the parser to expect a function expression is just to wrap in in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

// Either of the following two patterns can be used to immediately invoke
// a function expression, thus creating an anonymous closure with privacy.

(function(){ /* code */ })(); // I've been using this one
(function(){ /* code */ }()); // Crockford recommends this one

// Because the point of the parens or coercing operators is to disambiguate
// between function expressions and function declarations, they can be
// omitted when the parser already expects an expression (but please see the
// "important note" below).


In cases where the extra “disambiguation” parens surrounding the function expression are unnecessary (because the parser already expects an expression), it’s still a good idea to use them when making an assignment, as a matter of convention. Such parens typically indicate that the function expression will be immediately invoked, and the variable will contain the result of the function, not the function itself.

Properties

arguments

A local variable that points to the "arguments" object, which contains all of the arguments passed into the function. Use "arguments.length" to determine the number of arguments entered. You can use this property to define functions that accept varying number of parameters.

caller

References the function in which the current function is called inside of. If the current function is called at the top level, caller returns null. You can use this property to check the context in which a function is being called.

function myresidence(){
 calltest()
}

// alerts function myresidence(), 
// the function in which calltest() was called inside
myresidence() 

prototype

Lets you add custom properties and methods to a function's prototype object, which instantly adds them to all instances of the function initialized using the new operator (also called a constructor function). In the below, I'm adding a getprice() method to the constructor function Car() that is reflected on all instances of new Car():

function Car(baseprice, years_old){
 this.baseprice=baseprice
 this.history=years_old
}

//add method getprice() to all instances of Car (called using new Car())
Car.prototype.getprice=function(){
 this.price=this.baseprice - (this.history * 1000)
 alert(this.price)
}

var mytoyota=new Car(20000, 10)
mytoyota.getprice() //alerts 10,000

var myford=new Car(18000, 5)
myford.getprice() //alerts 13,000

You can also use the prototype object to extend prebuilt JavaScript objects that are initialized using the new operator with custom methods, such as with Date(), Array(), or String(). Lets extend the default String object with a backwards() method that takes a string and returns it backwards (ie: "george" becomes "egroeg"):

String.prototype.backwards=function(){
 var strlen=this.length, reversestr=''
 //loop through each char within string backwards
 for (var i=strlen-1; i>-1; i--) 
  reversestr+=this.charAt(i)
 return reversestr
}

document.write('george'.backwards()) //writes out "egroeg"

Methods

funcA.apply(funcB, [argument1, argument2, argumentN])

Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. Identical to call() below, except any arguments passed into funcA should be wrapped in an array.

funcA.call(funcB, argument1, argument2, argumentN)

Lets you call a function (funcA) as if it's a method of another function (funcB). Specifically, the "this" keyword when used inside funcA now returns funcB. The two methods apply() and call() are useful when you wish an object to "borrow" a method from another object and use it within its own context.

The following illustrates this:
function borrowme(name){
 this.bonus=(this.salary * 0.15) + (this.seniority * 500)
 alert(name + ", your bonus for this year is: " + this.bonus)
}

function employee(seniority, salary){
 this.seniority=seniority
 this.salary=salary
}

var employee1=new employee(10, 30000) 
//returns "Sarah, your bonus for this year is: 9500"
borrowme.call(employee1, "Sarah") 

Here the custom object "employee" uses the function "borrowme()" to manipulate a few numbers stored within it. Normally the keyword "this" in borrowme() references just that- the function itself. However, when it''s invoked using call(), the context of "this" changes so it references the object passed into the first parameter of call(), or in this case, "employee1".

apply() and call() are important tools in implementing inheritance in JavaScript.

toString()

Returns a string that represents the source code (raw text) of the function. A useful method in debugging, by looking at the source code of a function.

my thanks to:
http://www.javascriptkit.com/jsref/function.shtml
http://kangax.github.com/nfe/
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Responsive Web Design (using Media Queries)

0

Category :

CSS frameworks began winning fans by handling a lot of the grunt work for users, while offering familiar class names, structures and a set-width layout. When you knew the precise layout width, it was much easier to calculate columns and gutters.

With most displays/screens within such a limited range, it's easy to understand why both Blueprint and 960.gs (not to mention the many frameworks based on them) settled on a fixed 960 pixel-wide grid.

Fast forward to 2011, and there has never been more variation in the display ecosystem. Today, almost 30% of displays are larger than 1280 pixels—and 8% of these displays are wider than 1680 pixels. On the other hand, 960 pixels is often too wide to be truly useful on a slew of smartphones and smaller tablet devices.

Unfortunately, old-school fluid (or liquid) layouts aren't the answer. What single layout could work at 600 pixels and 1920 pixels? What we need are layouts that respond to the viewports they find themselves in.

Okay, but where do you start?

Most of these responsive layouts use CSS media queries. Media queries let us set simple tests that determine which parts of our CSS are rendered (and which aren't). For instance, you might say "if this is a monochrome display, use 'stylesheet X'".

Here's the syntax:


This line will attach the "small.css" stylesheet to our page, but only to devices with browser screens that are smaller than 1024 pixels. The moment the user resizes their browser window to a width larger than 1023px, the "small.css" is removed from the document.

CSSGrid.net

CSSGrid goes a little further than Less Framework by building in a complete 12-column layout framework.

Andy's approach works like this:

Wide screen: On large displays the layout scales fluidly up to 1139 pixels. At higher screen widths, the layout locks at 1140 pixels and centers your content.
Medium screen: On smaller desktop displays, the layout scales down fluidly until it reaches 768 pixels.
Smaller screen: On any device less than 768 pixels-wide (most often, but not exclusively, phones and smaller tablets), the layout automatically breaks down to a stacked single-column layout.
Demo........

We can let people make better use of their large displays without the risk of our content being strung out on super-wide monitors. This issue was always the killer blow to traditional fluid layouts.

On medium-sized desktops, I believe we have a much better experience than static 960-pixel grids. Sure, they can use almost all of their 1280-pixel display if that's what they want to do.

However, it's not uncommon for users to run launch bars, Twitter clients, or instant message apps on the right side of the screen. I know on my laptop, I'm unable to read any 960-pixel layout without it overlapping my Twitter client.

Allowing users to tailor your layouts to whatever space they have available helps both them and you.

There's not much argument that mobile users are becoming more widespread every day and Andy's CSSGrid provides an elegant solution out of the box. Content will stack vertically on any device less than 768 pixels wide. You write it once, and no device detection is required.

my thanks to:
http://www.sitepoint.com/newsletter/viewissue.php?id=5&issue=79