I use the following pattern in my JS:
var lib =
{
module_one:
{
init: function () {
...
}
},
module_two:
{
init: function () {
...
}
}
};
Question is, whats the best way to add:
(function ($) {
...
})(jQuery);
I tried to put it around the var lib, but that didnt work. To add it inside each function worked, but seems a bit messy..?
Is it possible to add it to the init: function($) somehow?
Quite new on jQuery, so if you have any other suggestions around this pattern, let me know 🙂
Basically, you can do this:
…which can then be used like this:
Here’s how that works:
thisvalue as a variable calledglobal. This will be the JavaScript global object because of the way we’re calling the scoping function. (The global object on browsers iswindow, but there’s no need to limit this to browsers, hence gettingglobalthis way).libproperty of the global object had, in a local variable in our scoping function calledoldlib.lib.noConflictfunction restores the earlier value of thelibproperty, and returns our lib reference so someone can use it as an alias.BTW, when you use a scoping function, you can also switch over to using named functions rather than anonymous ones, which has several benefits. Here’s the above updated to use a named function for
noConflict.