Monday, February 23, 2015

Javascript Namespaces

Google "namespace" and "javascript" and you'll get a lot of different approaches to the solution, since vanilla Javascript doesn't provide out of the box namespaces.  Here's how jQuery and others do it.  If you want the quick answers, you can skip the link and just copy paste from below. The solution is to create an anonymous function and call it immediately, associating it with the Javascript window object.

A few notes from me:


  1. My library doesn't load correctly.

    My library has some pre-reqs; the easiest solution was to wrap the declaration in jQuery's $().ready().  See below.  There are other better solutions for Javascript dependency management, but they weren't necessary.
  2. This is great, but underscore templating doesn't work INSIDE the namespace?  Ahh!?! What do I do?

    Well, here's the key parts of the sample solution.  Note that the function definition has three arguments.  The first is the namespace itself, then a $, then undefined.  The first argument's purpose is obvious, the last is a Javascript technicality; just include it.  You can add additional arguments in the middle. Note the call to the "namespace" function on the last line passes in jQuery for argument two, which maps jQuery to $.

    (function( skillet, $, undefined ) {
       //stuff
    }( window.skillet = window.skillet || {}, jQuery ));

    So if you want to use jQuery AND underscore, or any library for that matter, you'll have to add arguments to the definition and function call.  For openbrewery, the namespace declaration looks like this, defining and passing both $/jQuery and _/underscore:
    $().ready(function() {
       (function( openbrewery, $, _, undefined ) {
          //Stuff
       }( window.openbrewery = window.openbrewery || {}, jQuery, _ ));
    });


No comments:

Labels

Blog Archive

Contributors