Can a jQuery plug-in be local to a module?

I really like the JavaScript module pattern to encapsulate data and logic. I'm also using jQuery extensively. My question is this:

If I define a jQuery extension/plug-in WITHIN a module, will it be local to that module like other functions would be? (I suspect the answer is no...)

Example:

var igPartListManager = (function () {
    // Define a jQuery plug-in I'd like to be local to igPartListManager 
    (function ($) {
        $.fn.myExtension = function () {
            // Do something with this.each()...
        }
    })(jQuery);

    var doSomethingCore = function () {
        // Use my jQuery plug-in
        $("selector").myExtension();
    };

    return {
        doSomething
            : doSomethingCore
    };
})();

Outside of igPartListManager, would this succeed?

...
$("some_unrelated_selector").myExtension();

If it does, how do I best encapsulate 'local' jQuery-extension/plug-in-like functionality within a module?

Answers


To better explain this I made a little example of what actually happens when you define your extension:

(function ($) {
    // $ = window.jQuery;
    $.fn.myExtension = function () {
        // Do something with this.each()...
    }
})(window.jQuery); // Note window.jQuery is basically the same as just jQuery from your example code

Whenever you try to access a variable, the javascript engine bubbles up trough all encapsulating scopes all the way up to the window scope. The first scope that has that variable is the scope that is being used. Since in your case the window scope holds your jQuery variable you could call it 'global'.

When calling this $("some_unrelated_selector).myExtension(); the engine looks for the variable $. If this variable points to window.jQuery at that point, you are in fact using the same object as before. So yes, that would succeed in that case. But only if you executed the igPartListManager function before trying to call $().myExtension();.

The only way to create a local scope for your extensions is to deep copy the window.jQuery variable to a local variable before adding extensions to it.

Example: Javascript deep copying object


Need Your Help

Adding an html element to the jquery code of colorbox

jquery html object colorbox

I would like to add an element to jquery.colorbox.js(want to do some fancey styling)

PhoneGap - Call another application (AngryBirds)

android cordova native phonegap-plugins webintents

I'm implementing phonegap based application for android and want to call angry birds game from inside the phonegap app. After my quick research here and here I have following: