The Entertainment Shack

Feb 14 '12

 

Sep 2 '11

JavaScript objects and namespaces

If you want to pull out and namespace your JavaScript to make it simpler to unit test, or minify, I thought I'd share the pattern that I have been using:

In the external JavaScript file:

// Setup Namespaces
if (typeof com == 'undefined') { com = {}; }
if (typeof com.mycompany == 'undefined') { com.mycompany = {}; }
if (typeof com.mycompany.project == 'undefined') {
com.mycompany.project = {}; }

com.mycompany.project.widget = function (config) {
   var defaults = {
       someselector: null,
   };

   // Merge defaults with what's passed in
   var config = $.extend(true, {}, defaults, config);

   var init = function () {
       someselector.html("hello world");
   }

   // Expose functions and properties
   return {
       init: init
   }
}

Then on your page:

widgetLogic = com.mycompany.project.widget({
    someselector: $("#mydiv"),
});
widgetLogic.init();

listed in: javascript |

 

Jul 4 '11

 

Feb 2 '09

 

Sep 13 '08

 

Aug 3 '07

 

Apr 24 '06