How to work with jQuery no-conflict mode and multi

2019-09-11 01:08发布

问题:

What a crappy title. Maybe someone can edit it for me. Here's the scoop:

I need to work in jQuery no-conflict mode, but I'd still like to take advantage of the $ shortcut, so all of my functions etc are defined within the typical closure of (function($){ ... })(jQuery);

All this is defined in an external source.js file that is included at the top of my HTML web page.

A little later on, I need to add some inline <script> that uses one of the utility functions I defined within the closure. Obviously I've namespaced myself into a box and can't access that function.

What's the right pattern to use here?

回答1:

To control how much and what you expose in the global namespace, it is custom to expose what you need through one global object, usually in all capital letters.

FOO.module1.init();
FOO.module2.init();

You would do this by making sure FOO exists, and if it doesn't: create it.

var FOO = this.FOO || {};

The same for your module namespaces:

FOO.module1 = FOO.module1 || {};

and then inside of the anonymous function, expose what you want.

Complete example

module1.js:

var FOO = this.FOO || {};
FOO.module1 = FOO.module1 || {};

(function ($) {
    var my, local, data;

    function init() {
        // use my, local and data here.
    }

    FOO.module1.init = init;
}(jQuery));

module2.js:

var FOO = this.FOO || {};
FOO.module2 = FOO.module2 || {};

(function ($) {
    var some, other, data;

    function init() {
        // use some, other and data here.
    }

    FOO.module2.init = init;
}(jQuery));

controller.js:

FOO.module1.init();
FOO.module2.init();


回答2:

Magnar's answer is the way to go for anything complex. But just for the sake of completeness, for something very simple you can just make it global like this:

$.noConflict();

(function($){
    window.doSomething = function(){
        $("body").css("background-color","red");
    }        
})(jQuery);


doSomething();

by adding the function to window it becomes global.

http://jsfiddle.net/cxTYV/