2010-09-08 83 views
1

我用下面的方式在我的JS:如何将noConflict添加到JS模块模式?

var lib = 
{ 
    module_one: 
    { 
     init: function() { 
      ... 
     } 
    }, 
    module_two: 
    { 
     init: function() { 
      ... 
     } 
    } 
}; 

的问题是,什么最好的方式来增加:

(function ($) {   
    ... 
})(jQuery); 

我试图把它挂在了var LIB,但没有工作。要在每个函数内部添加它,但似乎有点凌乱..?

是否有可能以某种方式将它添加到init:function($)?

相当新的jQuery的,所以如果你有解决这个模式的任何其他建议,让我知道:-)

+0

什么是'lib'意图是一个全局变量? – 2010-09-08 10:05:12

回答

3

基本上,你可以这样做:

(function() { 
    var global, lib, oldlib; 

    // We call this anonymous scoping function directly, so we know that 
    // within it, `this` is the JavaScript global object. Grab a 
    // local reference to it so we can use it within functions that get 
    // called via dotted notation and so have different `this` values. 
    global = this; 

    // Remember any value that already exists for the `lib` property 
    // of the global 
    oldlib = global.lib; 

    // Define our lib, assigning it to a local variable 
    lib = { 
     /* ...your stuff as usual, plus: */ 

     noConflict: function() { 
      global.lib = oldlib; 
      return lib; 
     } 
    }; 

    // Publish our lib externally on the global object 
    global.lib = lib; 
})(); 

...这可以再使用这样的:

var alias = lib.noConflict(); 

这里是如何工作的:

  1. 我们定义了一个范围函数,然后立即调用它。
  2. 在范围函数中,我们获取this值作为变量global。由于我们调用范围函数的方式,这将成为JavaScript全局对象。 (浏览器上的全局对象是window,但不需要限制浏览器,因此以这种方式获得global)。
  3. 我们要做的第一件事就是保存全局对象的lib属性的任何旧值,在我们的作用域函数oldlib的局部变量中。
  4. 我们为lib设置了新值。
  5. 我们的noConflict函数恢复lib属性的较早值,并返回我们的lib引用,以便有人可以使用它作为别名。

顺便说一句,当你使用范围函数时,你也可以切换到使用命名函数而不是匿名函数,其中has several benefits。以上是使用noConflict的命名函数进行更新的方法。

(function() { 
    var global, lib, oldlib; 

    // We call this anonymous scoping function directly, so we know that 
    // within it, `this` is the JavaScript global object. Grab a 
    // local reference to it so we can use it within functions that get 
    // called via dotted notation and so have different `this` values. 
    global = this; 

    // Remember any value that already exists for the `lib` property 
    // of the global 
    oldlib = global.lib; 

    // Define the functions for our lib. Because they're defined 
    // within our scoping function, they're completely private 
    function lib_noConflict() { 
     global.lib = oldlib; 
     return lib; 
    } 

    // Define our lib, publishing the functions we want to be public 
    lib = { 
     /* ...your stuff as usual, plus: */ 

     noConflict: lib_noConflict 
    }; 

    // Publish our lib externally on the global object 
    global.lib = lib; 
})();