是否可以通过绑定发送绑定到 mootools 类的事件的目标?
IE:
checkbox.addEvent('change', this.checkBoxChangeAgain(this));
哪里this
==checkbox
附言。这不起作用:
checkbox.addEvent('change', this.checkBoxChangeAgain(checkbox));
是否可以通过绑定发送绑定到 mootools 类的事件的目标?
IE:
checkbox.addEvent('change', this.checkBoxChangeAgain(this));
哪里this
==checkbox
附言。这不起作用:
checkbox.addEvent('change', this.checkBoxChangeAgain(checkbox));
它不起作用的原因是通过这样做,method(this)
您实际上会立即调用它。method.bind(checkbox)
将装饰函数并将范围更改为稍后调用时的复选框。
为什么不代理呢?
var self = this;
checkbox.addEvent('change', function(e) {
self.checkBoxChangeAgain(this);
});
new Class({
checkBoxChangeAgain: function(checkbox) {
this; // instance
checkbox; // == org checkbox
}
});
默认情况下,事件处理程序的第一个参数是事件,作用域是触发器元素。
因此:
checkbox.addEvent('change', this.checkBoxChangeAgain);
将意味着:
new Class({
checkBoxChangeAgain: function(event) {
this === event.target;
}
});
这意味着您还可以:
checkbox.addEvent('change', this.checkBoxChangeAgain.bind(this));
这将作为:
new Class({
checkBoxChangeAgain: function(event) {
this != event.target; // true
event.target === checkbox; // true
this; // the class instance
}
});
我希望这能给你一些想法。此外,在 SO 上搜索 bindWithEvent - 特别是用事件替换绑定。
类似于 Dimitar 的答案的工作原理,但使用 Class.Binds,最简单的方法是使用.pass()
http://mootools.net/docs/core/Types/Function#Function:pass
this.checkBoxChangeAgain.pass(checkbox)