如何使用jQuery无冲突模式和多个脚本位置 [英] How to work with jQuery no-conflict mode and multiple script locations

查看:114
本文介绍了如何使用jQuery无冲突模式和多个脚本位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个。脚的标题。也许有人可以为我编辑它。这里是勺子:



我需要工作在jQuery无冲突模式,但我仍然想利用$快捷方式,所有我的所有功能等在(function($){...})(jQuery);

的典型关闭中定义

所有这些都在一个外部source.js文件中定义,该文件包含在我的HTML网页的顶部。



稍后,我需要添加一些inline < script> ,它使用闭包中定义的一个效用函数。显然我把命名空间放在一个框中,不能访问该函数。



这里使用的正确模式是什么?

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

你可以通过确保FOO存在来做到这一点,如果没有:创建它。 / p>

  var FOO = this.FOO || {}; 

您的模块命名空间也是如此:

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

然后在匿名函数里面暴露你想要的东西。



完成示例



module1.js:

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

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

function init(){
//使用my,local和data
}

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
}

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

controller.js

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


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?

解决方案

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();

这篇关于如何使用jQuery无冲突模式和多个脚本位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆