Mootools - 绑定到类实例并访问事件对象

时间:2010-08-12 14:45:36

标签: mootools

我有一个触发onFocus事件的组件。我正在分配一个类方法来处理onFocus事件。在事件处理程序中,我需要访问类实例和事件对象本身。

但是,当我使用.bind(this)时,我无法再获取事件对象,因为范围现在已更改为类实例。如果我不使用.bind(this),我可以访问事件对象,但不能访问类实例。

我确信有一个解决方案,但我无法解决这个问题。有什么想法吗?

感谢。

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

1 个答案:

答案 0 :(得分:2)

你能发布更多吗?基本上 - 类的骨架以及调用BasePickList的新实例的函数。看看事件是如何被触发的,BasePickList源也不会受到伤害。

现在,您不需要使用.bind(this)包装类方法,它会自动执行此操作。至于事件,取决于激发它们的内容,如果这是一个输入字段,那么它应该传递原始事件,你可以通过handleComponentFocus: function(e) {来捕获,其中e将是事件对象。

这可能与你想要做的事情有所不同,但它可能会给你一些想法 http://www.jsfiddle.net/dimitar/KdhvG/

在关注字段时检查控制台输出 - 它将控件传递给带有事件对象的handleComponentFocus方法(带有指向复选框的event.target)以及类实例的范围

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