简体   繁体   English

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

[英]JavaScript Namespace & jQuery Event Handler

I have created a Javascript namespace to avoid conflict with other Javascript codes. 我创建了一个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 ...
   }
};

Please, how can I reference my enclosing namespace? 请问,我如何引用我的封闭命名空间?

$ .proxy

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

You can bind event handler to an anonymous function and call clickHandler within it. 您可以将事件处理程序绑定到匿名函数,并在其中调用clickHandler This way the context will still refer to ns object. 这样上下文仍将引用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 ...
   }
};

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

It explains to create a closure in the namespace where you can store stuff (like the original 'this') 它解释了在命名空间中创建一个闭包,你可以在那里存储东西(比如原来的'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 ...
        }
    };
})();

FIDDLE HERE 骗子在这里

A good way to do that is to define a local variable in a function that refers to it. 一个好方法是在引用它的函数中定义局部变量。 This helps when "this" changes on you. 当“这个”改变你时,这会有所帮助。 Your code could look something like this: 您的代码可能如下所示:

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 allows you to still reference the event handler with this and then reference your namespace with the locally defined reference that is only available from within. 这允许您仍然使用this引用事件处理程序,然后使用仅在内部提供的本地定义的引用引用您的命名空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM