2013-06-19 37 views
3

我创建了一个Javascript命名空间以避免与其他Javascript代码冲突。JavaScript命名空间和jQuery事件处理程序

var ns = { 
    init: function() { 
     $('a').click(this.clickHandler); 
    }, 
    clickHandler: function() { 
     // Some code here .. 

     // The keyword "this" does not reference my "ns" object anymore. 
     // Now, it represents the "anchor" 
     this.updateUI(); 
    }, 
    updateUI: function() { 
     // Some code here ... 
    } 
}; 

请问我该如何引用我的封闭名称空间?

回答

6

$.proxy

$('a').click($.proxy(this.clickHandler, this)); 
+0

谢谢你这么创建一个封闭太多了! – Ammar

4

您可以事件处理程序绑定到一个匿名函数,并调用其内部clickHandler事件。通过这种方式,上下文仍将引用ns对象。

var ns = { 
    init: function() { 
     var self = this; // store context in closure chain 
     $('a').click(function() { 
     self.clickHandler(); 
     }); 
    }, 
    clickHandler: function() { 
     this.updateUI(); 
    }, 
    updateUI: function() { 
     // Some code here ... 
    } 
}; 
+0

'this'如何在clickHandler函数中获得正确的值? –

+0

@LeeMeador,上下文指向dom对象的事件处理程序中的dom对象。在我们的匿名事件处理程序中,上下文指向dom元素,我们使用闭包变量来获取原始上下文。最后,当clickHandler调用时,它将具有正确的上下文,因为它由ns对象调用。 – halilb

+1

我明白了。还在搞清楚'this'/ context是如何设置的。我在这里试过,以防其他人想看到它。 http://jsfiddle.net/LMaBq/ –

0

一个好方法是在引用它的函数中定义一个局部变量。这有助于“此”在您身上发生变化。你的代码可能是这个样子:

var ns = new (function() { 
    var self = this; 
    self.init = function() { 
     $('a').click(self.clickHandler); 
    }, 
    self.clickHandler = function() { 
     // Some code here .. 

     // The keyword "this" does not reference my "ns" object anymore. 
     // Now, it represents the "anchor" 
     self.updateUI(); 
    }, 
    self.updateUI = function() { 
     // Some code here ... 
    } 
})(); 

这使您可以仍引用事件处理程序这一点,然后用本地定义的引用,只能从内引用您的命名空间。

+0

这根本行不通。 – Pointy

+0

以这种方式上下文将指向点击dom元素。 – halilb

+0

它可以像这里显示的那样修复http://jsfiddle.net/JYAXL/ - 只需要一个更改。问题在于,'self'会在创建对象时被赋予'ns'的时候获取上下文值('this'的值)。 –

1

这里是一个文章:http://www.codeproject.com/Articles/108786/Encapsulation-in-JavaScript

它说明了在那里你可以存储的东西(像原来的“本”)的命名空间

var ns = (function() { 
    var self; 

    return { 
     init: function() { 
      self = this; 
      $('a').click(this.clickHandler); 
     }, 
     clickHandler: function() { 
      // Some code here .. 
      self.updateUI(); 
     }, 
     updateUI: function() { 
      // Some code here ... 
     } 
    }; 
})(); 

FIDDLE HERE