Search code examples
javascriptjqueryjavascript-namespacesiife

IIFE jquery ready


I am working on a web project that has a large amount of javascript and we started hitting namespace collisions because we were adding everything to "$.".

I read up about namespacing and found the great article at http://addyosmani.com/blog/essential-js-namespacing/

I tried to set up the namespace inside of an IIFE as recommended and thought I was in luck because the function was already setup as

(function() { ... }); 

so I converted it to:

(function(namespace, undefined) { ... })(window.stuff = window.stuff || {});

only to find (after hours of work) that actually the original was

$(function() { ... }

Which means it was all being called in jQuery's ready() function.

I would like to keep the namespacing IIFE but cannot figure out how I would use it within jQuery's ready() function. Is this possible and if so how?


Solution

  • var namespace = (function() {
        // local variables and functions
    
        function readyHandler($) {
             // DOM ready code
             $("selector").method();
        }
    
        // exposed methods
        return {
            readyHandler: readyHandler
        };
    })();
    
    jQuery(namespace.readyHandler);