February 23, 2013

Javascript Closures

I thought I’d take a moment to share my Javascript Closure template which I use regularly. Its a great way to namespace your functions and encapsulate functionality into packages. This is another helpful resource if you want to learn more about why we do it.

ProTip: If you’re a Visual Studio developer, this code snippet may save you a little time. Just change the suffix to .snippet and store in your code snippets folder.

var Namespace = function () {

    return {

        Init: function () {
            //if anything needs to be inited, it can be done here
        },

        PublicFunction: function (args) {

            //Need fully qualify function when calling
            //a from within the namespace
            Namespace.AnotherPublicFunction(args);

            //fully qualified not needed for private functions
            _privateFunction(args);

        },

        AnotherPublicFunction: function(args){
        }
    };

    function _privateFunction : function(args){
    }
} ();
August 10, 2012

Javascript Namespacing

I’ve written before about javascript closures which are incredibly helpful and very tidy once you understand what they’re doing. However, I have some a new code template I use when namespacing my javascript libraries. First rule of thumb is to never pollute the global namespace; you should always define your functions within some larger object. This will prevent naming collisions and keep things very very tidy.

Lets say I want to call my library MyLibrary and I want to organize code within the library into two areas: Area1 and Area2. First thing we want to do is to create the root object.

if (typeof(MyLibrary) == 'undefined')
   MyLibrary = {};

Here we’re just checking that MyLibrary is not already defined. If its not, we’ll create the new object so we can attach more things to it.

After that, its just a matter of using a javascript closure to attach more objects/functions to the root object

(function(ml){

    s.Area1 = (function(){
	return {
		publicFunc : function(){
			console.log('Area 1 public function');
		}
	};
    })();

    s.Area2 = (function(){
	return {
		publicFunc : function(){
			console.log('Area 2 public function');
		}
	};
    })();

})(MyLibrary);

Now in my code, I can call MyLibrary.Area1.publicFunc(); and MyLibrary.Area2.publicFunc(); I can add as many areas to MyLibrary as I please.

As long as I include the undefined check at the top of my files, I can split MyLibrary up into as many files as I like which can give me added flexibility to only apply functionality to certain pages.

April 30, 2012

jQuery Plugin Template

I wanted to share a jQuery plugin template that I use. There are a lot of templates out there but I found this one fairly straight forward to use and provided all the necessary functionality.

What I really needed was a plugin that would provide some helper functions on it. I’ve seen a lot of plugins that did something to the html and attached events but I rarely found any that had public functions done in a way that made sense to me. After doing some Googling, I found something I liked and tweaked it a bit.

(function($){

    var methods = {

        init: function(options){
            return this.each(function() {
               //init each element here
            });
        },

        sampleFunction : function(){

        }

    };

    $.fn.pluginName = function(method){

        if(methods[method]) {
          return methods[method].apply(this,
                        Array.prototype.slice.call(arguments, 1));
        }
        else if(typeof method === 'object' || !method) {
          return methods.init.apply(this, arguments);
        }
        else {
          $.error("Method " +  method + " does not exist");
        }

    }

})(jQuery);

Thats it! It’ll let me do things like this:

$('div').pluginName(); //init code
$('div').pluginName({foo:'bar'}); //init with options
$('div').pluginName('sampleFunction'); //function