IIFE jquery ready
-
29-06-2021 - |
Pergunta
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?
Solução
var namespace = (function() {
// local variables and functions
function readyHandler($) {
// DOM ready code
$("selector").method();
}
// exposed methods
return {
readyHandler: readyHandler
};
})();
jQuery(namespace.readyHandler);
Outras dicas
Mmm, not sure if you got the concepts straight... None of those functions looks like an Immediately Invoked Function Expression because you're not invoking the function.
(function() { ... } ());
--^-- invoke function
jQuery's ready
already creates a new closure so you don't need an IIFE anyway.
In any case, when using jQuery you can namespace your plugin in the $
namespace with an object that way you don't pollute it.
$.myplugin = {
...
}