JavaScript命名空间&jQuery事件处理程序

JavaScript Namespace & jQuery Event Handler

本文关键字:事件处理 程序 jQuery 命名空间 JavaScript      更新时间:2023-09-26

我已经创建了一个Javascript命名空间,以避免与其他Javascript代码冲突。

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 ...
   }
};

请问,我如何引用我的封闭命名空间?

$.proxy

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

您可以将事件处理程序绑定到匿名函数,并在其中调用clickHandler。这样,上下文仍然会引用ns object。

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 ...
   }
};

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

它解释了在命名空间中创建一个闭包来存储东西(比如原来的'this')

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 ...
        }
    };
})();
这里的

小提琴

这样做的一个好方法是在引用它的函数中定义一个局部变量。当"这个"在你身上发生变化时,这很有帮助。您的代码可能看起来像这样:

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

这允许您仍然使用This引用事件处理程序,然后使用仅在内部可用的本地定义引用引用您的命名空间。