从绑定到事件的另一个函数调用绑定到事件的函数不起作用

时间:2012-02-14 17:44:08

标签: javascript jquery slickgrid

我正在为slickgrid制作一个自定义编辑器,虽然我怀疑在这种情况下我真正重要的是什么。所以,假设我有类似这样的设置:

function TestEditor(args) {
 var $test0, $test1;
 //other variables

 this.init = function () {
  //various init stuff, it all works fine
  //init $test0 and $test1, also works fine

  $test0.bind("change", this.test0Changed);
  $test1.bind("change", this.test1Changed);

  this.test0Changed(); //this works fine too, makes the nested call to test1Changed
 }

 this.test0Changed = function() {
  //does various operations
  this.test1Changed(); //calls test1Changed, this works _unless_ test0Changed is called through an event, then the code breaks here!
  //stuff that won't happen when the code breaks at the previous call
 }

 this.test1Changed = function() {
  //stuff, works fine unless called by test0Changed triggered by an event, then nothing
 }

 //whatever, lots of other stuff, it all works

 this.init();
}

我希望test0Changed调用test1Changed,如果我在代码中明确地调用this.test0Changed(),它就可以正常工作。但是当'change'事件触发test0Changed时,代码在尝试调用this.test1Changed()时会中断。如果我注释掉对this.test1Changed()的调用,一切都很好,所以我知道这是引起问题的精确线。造成这种情况的原因是什么?

1 个答案:

答案 0 :(得分:3)

这是因为当您使用.bind()函数时,它不会“记住”初始this值。

作为处理程序,this将是接收事件的元素。

this.init = function () {

   var self = this;

   $test0.bind("change", function() {self.test0Changed.apply(self, arguments);});
   $test1.bind("change", function() {self.test1Changed.apply(self, arguments);});

 }

这里我引用了你想在变量中使用的this,并且我传递了使用引用的this值的匿名函数来调用函数。


我还使用.apply来确保传递所有原始参数。如果没有必要,您可以将其更改为此...

this.init = function () {

   var self = this;

   $test0.bind("change", function() {self.test0Changed();});
   $test1.bind("change", function() {self.test1Changed();});

 }

或者您可以使用jQuery的$.proxy来保留this值......

this.init = function () {

   $test0.bind("change", $.proxy(this, 'test0Changed'));
   $test1.bind("change", $.proxy(this, 'test1Changed'));

 }