2012-02-14 82 views
0

我正在为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(),它工作正常。但是当test0Changed被'change'事件触发时,代码在试图调用this.test1Changed()时会中断。如果我注释掉对this.test1Changed()的调用,一切都很好,所以我知道是导致问题的那条精确线。这是什么造成的?

+0

什么'测试变量在虚线上注明? – paislee 2012-02-14 17:46:06

+0

哎呀,这是愚蠢的,我的意思是这个 – user173342 2012-02-14 17:47:19

回答

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')); 

} 
+0

哦,有没有什么办法在这种情况下得到这个呢?并让它适用于这两种呼叫? – user173342 2012-02-14 17:52:24

+0

语法?关闭'}' – paislee 2012-02-14 17:54:42

+0

谢谢@paislee:我会更新。 – 2012-02-14 17:56:39

相关问题