【问题标题】:Call the methods in mootools class调用 mootools 类中的方法
【发布时间】:2009-10-16 23:10:59
【问题描述】:
我有一个关于在 mootools 类中调用其他函数的问题。例如:
var f = new Class('foo',
{
test1: function(){
var table = new Element(...);
...
$(table).getElements('input').each(function(input) {
input.addEvent('change', function() {
// how could I call test2 and pass the input element?
})
});
},
test2: function(e){
alert(e);
}
});
谢谢。
【问题讨论】:
标签:
javascript
methods
mootools
【解决方案1】:
var f = new Class('foo',
{
test1: function(){
var table = new Element(........);
var me = this;
$(table).getElements('input').each(function(input) {
input.addEvent('change', function() {
me.test2("foo");
});
});
},
test2: function(e){
alert(e);
}
});
【解决方案2】:
如果可以的话,最好使用 bind。我会像这样重构它(如果您不需要传递触发器元素本身,否则,您可以从 event.target 属性中获取它)
var f = new Class('foo', {
test1: function() {
var table = new Element(........);
// no need to use $(), table is already an object.
table.getElements('input').addEvents({
change: function(e) {
this.test2(e);
}.bind(this) // bind the function to the scope of the class and
// not the element trigger
});
},
test2: function(e){
var e = new Event(e);
console.log(e.target);
}
});
在这里查看:http://mooshell.net/rWUzN/
【解决方案3】:
您必须使用 bindWithEvent 在您的函数中同时获取事件和 this,而且您不需要调用每个因为 mootools 会为您执行此操作:
var f = new Class('foo',
{
test1: function(){
var table = new Element(........);
table.getElements('input').addEvent('change', this.test2.bindWithEvent(this));
},
test2: function(e){
alert(e);
}
});