Monday, February 28, 2011

Essential JavaScript Design Patterns

Link: Essential JavaScript Design Patterns

A very good reference outlining the implementation of common design patterns in JavaScript.

Wednesday, February 23, 2011

RequireJS

Dependency management and modularization are hot topics in JavaScript right now. In classical OO languages like C#, we often take dependency management for granted, as there is an abundance of tools available for this purpose. JavaScript is a powerful, flexible language but still sorely lacking in the tools sector. Traditionally, dependencies have been manually configured by specifying script tags in transitive dependency order. This approach, while effective, becomes tedious and difficult to maintain as the volume of scripts grows. In today’s large-scale JavaScript applications, streamlined and efficient dependency management is becoming more and more crucial.

Related to dependency management is the modular approach to designing JavaScript applications, separating functionalities into physically separate files roughly following OOP’s single responsibility principle: http://en.wikipedia.org/wiki/Single_responsibility_principle. Clearly, this approach lends itself to a large number of files in all but the simplest applications, and dependency management/module load order then becomes critical.

Fortunately, the JavaScript community has taken note, and tools are emerging to bridge these gaps. Among those I researched as candidates were:

YUI Loader from Yahoo: http://developer.yahoo.com/yui/yuiloader/
StealJS, part of JavaScriptMVC: http://www.javascriptmvc.com/docs/stealjs.html#&who=stealjs
Lab.js: http://labjs.com/
RequireJS: http://requirejs.org

As of this writing, I’m leaning towards RequireJS for a couple of significant reasons:

1) It’s a port of the proposed CommonJS specification for modular JavaScript. CommonJS (http://www.commonjs.org/) came out of the server-side JavaScript movement, and defines an API by which functionality can be packaged into interoperable JavaScript modules. CommonJS is gaining real traction, and has a strong change at widespread acceptance.

2) The syntax required to define RequireJS modules imposes minimal impact on how I write modules. It essentially entails just wrapping my modules in the API’s define() function:

//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define([“./cart”, “./inventory”], function(cart, inventory) {
        //return an object to define the “my/shirt” module.
        return {
            color: “blue”,
            size: “large”,
            addToCart: function() {
                inventory.decrement(this);
                cart.add(this);
            }
        }
    }
);

So far, I’m really pleased with the implementation. Modules explicitly describe their own dependencies, and the API ensures a file is only loaded once. The API uses asynchronous script loading via insertion of script tags in the document head, allowing browser-legal cross-domain requests. You can specify multiple script paths, and define multiple object contexts so that multiple instances of a module can be defined in a single page.

This is a very powerful, well thought-out API that looks like a good candidate for effective and efficient module loading and dependency management. I’ll post more as I dig deeper…


Tuesday, February 22, 2011

jsFiddle - A Playground For Web Developers

From jsFiddle.net:


JsFiddle is a playground for web developers, a tool which may be used in many ways. One can use it as an online editor for snippets build from HTML, CSS and JavaScript. The code can then be shared with others, embedded on a blog, etc. Using this approach, JavaScript developers can very easily isolate bugs.”

Friday, February 18, 2011

JavaScript Closures

Closures are one of the most powerful features of the JavaScript language, and also one of the least understood. Simply put, a closure is an object that retains access to the lexical scope in which it was created. Remember that in JavaScript, functions are first class objects, they can be assigned to variables, passed as arguments etc.


Take the following example:


        function myFunction() {
            var i = 0;
            return function () {
                alert(++i);
            };
        };

        var myFunction2 = myFunction(); //myFunction is now out of scope
        myFunction2(); //displays 1
        myFunction2(); //displays 2
        myFunction2(); //displays 3


What happened? The function returned by myFunction retains access to the local variable i - this is a closure. JavaScript maintains not just the returned function, but a reference to the environment in which it was created - including all the local variables in scope at that time.


So, why is this useful? Well, one excellent use is encapsulation, allowing an object to expose a public API whilst keeping it’s internal data and functionality private.


Consider this example:


        function myObject() {
            var i = 0;

            function increment() {
                return ++i;
            };

            function decrement() {
                return —i;
            };

            return {
                PlusOne: function () {
                    alert(increment());
                },
                MinusOne: function () {
                    alert(decrement());
                }
            };
        };

        var myObjectInstance = myObject();

        myObjectInstance.i = 1; //fails, private variable
        myObjectInstance.increment(); //fails, private function
        myObjectInstance.PlusOne(); //displays 1
        myObjectInstance.PlusOne(); //displays 2
        myObjectInstance.MinusOne(); //displays 1


Our MyObject function has a locally-scoped variable “i”, and two locally-scoped functions, “increment” and “decrement”. The return value is an object (defined with object literal notation) that defines two functions, “PlusOne” and “MinusOne”. These functions are public, but they access the private functions “increment” and “decrement” via the closure provided by myObject’s context. This is starting to look a little like private methods and variables in classical OO…


Taking it one step further, we can introduce a variation on the classic GoF singleton pattern by making the function execute and return immediately with the following syntax:


        var myObject = (function () {
            var i = 0;

            function increment() {
                return ++i;
            };

            function decrement() {
                return —i;
            };

            return {
                PlusOne: function () {
                    alert(increment());
                },
                MinusOne: function () {
                    alert(decrement());
                }
            };
        })();


Our object is now instantiated and ready to use:


        myObject.PlusOne();
        myObject.PlusOne();


This is generally referred to as the JavaScript Module Pattern, and attributed to Douglas Crockford. For a concise synopsis: http://www.yuiblog.com/blog/2007/06/12/module-pattern/. It’s a very useful pattern, lending itself to modularization of JavaScript code.


There are pitfalls, some of which I’ll go into in future posts. However, carefully used closures lend themselves to clean, powerful, maintainable JavaScript code.


Thursday, February 17, 2011

JavaScript Namespaces

As your JavaScript applications become more complex, it is imperative that you namespace your scripts to avoid naming conflicts and avoid polluting the global namespace. (i.e., the window object)


JavaScript has no built-in support for namespaces, but you can simulate them by assigning your functions as properties of an object.


var NameSpaces = {
    Register: function (namespace) {
        var nsParts = namespace.split(“.”);
        var root = window;

        for (var i = 0; i < nsParts.length; i++) {
            if (typeof root[nsParts[i]] == “undefined”)
                root[nsParts[i]] = new Object();

            root = root[nsParts[i]];
        }
    }
};

NameSpaces.Register(“My.Namespace”);


My.Namespace.myFunction = function() {

};


You can now call your new function as My.Namespace.myFunction(), which is uniquely scoped to the window.My.Namespace object, and safely avoid conflict with any other “myFunction” that might appear in another loaded script. Namespacing your functions also keeps the global namespace clean and uncluttered.


Thanks to Michael Shwarz for the Register function in the above closure: http://weblogs.asp.net/mschwarz/archive/2005/08/26/423699.aspx


Quote for the day

It is not usually until you’ve built and used a version of the program
that you understand the issues well enough to get the design right.

—Brian Kernighan, Rob Pike, The Practice of Programming

Wednesday, February 16, 2011

Underwater Photography

Link: Underwater Photography

Some photos I’ve taken underwater over the past five years. I don’t have a working camera right now, but I hope to get back to this very expensive and time consuming hobby soon!

JavaScript Goodness

I’ve been working with JavaScript quite a bit lately. It’s been part of my skill set for years, but largely for simple DOM manipulation, validation, alerts and the like. With the advent of AJAX, popular libraries that abstract cross-browser constraints, and widespread adoption of JSON as a payload format, JavaScript seems more than ever to be poised for prime time. Add to this the growing number of server-side implementations like Node.js, and JavaScript represents possibly the most important language in web development today.


So, I’ve been digging deeper into client-side application development with JavaScript, and learning a lot in the process of moving from server-side and classical OO development. Libraries such as jQuery, Prototype, and MooTools started to pique my interest a few years ago, and jQuery in particular has become part of my standard toolbox these days. Its clean, closure-based, highly extensible design has made it extremely popular and for good reason.


Recently, jQuery got a huge boost when Microsoft started supporting the library, both by bundling it with Visual Studio and now by contributing directly to the jQuery community with three official jQuery plugins: http://weblogs.asp.net/scottgu/archive/2010/10/04/jquery-templates-data-link-and-globalization-accepted-as-official-jquery-plugins.aspx


Two of these plugins, Templates and DataLink, got me started on a proof of concept at work combining them with ASP.NET MVC 3 to serve JSON payloads to the client application. From there I started digging deeper into JavaScript itself, looking at some more advanced concepts including implementing some of the classic GoF patterns within the context of JavaScript.


In coming posts I’ll share some of what I’ve learned along the way, hoping to shed some light on the ubiquitous but largely underestimated language that is JavaScript.