Mootools-绑定到类实例并访问事件对象 [英] Mootools - Bind to class instance and access event object
问题描述
我有一个触发onFocus事件的组件.我正在分配一个类方法来处理onFocus事件.在事件处理程序中,我需要访问类实例和事件对象本身.
I have a component that fires an onFocus event. I am assigning a class method to handle the onFocus event. In the event handler I need access to both the class instance, and the event object itself.
但是,当我使用.bind(this)时,由于范围已更改为类实例,因此无法再获取事件对象.如果我不使用.bind(this),则可以访问事件对象,但不能访问类实例.
However, when I use .bind(this), I can no longer get the event object because the scope is now changed to the class instance. And if I don't use .bind(this) I can access the event object, but not the class instance.
我确定有解决方案,但是我无法弄清楚.有什么想法吗?
I'm sure there is a solution, but I have not been able to figure this out. Any ideas?
谢谢.
new Class( {
handleComponentFocus : function() {
// this refers to the class instance
// I would also like to get the event information as well, but can't now that the scope has been changed
}.bind(this)
this.pickList = new BasePickList( {
onFocus : this.handleComponentFocus
});
})
推荐答案
您可以发布更多吗?基本上-类的骨架以及调用BasePickList
的新实例的函数.看到事件是如何触发的,BasePickList源代码不会受到损害.
can you post more? basically - a skeleton for the class as well as the function where you call up a new instance of BasePickList
. BasePickList source wouldn't hurt to see how the event is fired.
现在,您不需要使用.bind(this)
包装类方法,它会自动执行.至于事件,取决于触发它们的原因,如果这是一个输入字段,那么它应该传递原始事件,您可以通过handleComponentFocus: function(e) {
捕获该事件,其中e是事件对象.
now, you don't need to do wrap the class method with a .bind(this)
, it does that automatically. as for events, depends on what fires them, if this is a input field then it ought to pass on the original event which you can capture via handleComponentFocus: function(e) {
where e will be the event object.
这可能与您尝试执行的操作有所不同,但可能会给您一些想法 http://www.jsfiddle.net/dimitar/KdhvG/
this may be waaay off from what you are trying to do but it may give you some ideas http://www.jsfiddle.net/dimitar/KdhvG/
当您专注于该字段时,请检查控制台输出-它会将控制权与事件对象(指向复选框的event.target一起完成)以及类实例的范围传递给handleComponentFocus
方法. /p>
check console output when you focus on the field - it passes on control to the handleComponentFocus
method with the event object (complete with event.target that points to the checkbox) as well as a scope of the class instance.
<input type="checkbox" id="foo" />
和
var banana = new Class({
Implements: [Events, Options],
initialize: function(options) {
this.setOptions(options);
this.element = document.id(this.options.element);
this.element.addEvents({
focus: function(e) {
this.fireEvent("focus", e);
}.bind(this)
});
}
});
var foo = new Class({
handleComponentFocus: function(e) {
console.log(e);
},
initialize: function() {
this.picklist = new banana({
element: "foo",
onFocus: this.handleComponentFocus
});
}
});
new foo();
这篇关于Mootools-绑定到类实例并访问事件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!