3

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

囲んでいる名前空間を参照するにはどうすればよいですか?

4

4 に答える 4

6

$.proxy

$('a').click($.proxy(this.clickHandler, this));
于 2013-06-19T16:04:47.020 に答える
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 ...
   }
};
于 2013-06-19T16:06:43.453 に答える