代码之家  ›  专栏  ›  技术社区  ›  Steve

moootools-绑定到类实例和访问事件对象

  •  1
  • Steve  · 技术社区  · 14 年前

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

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

    我肯定有解决办法,但我一直没能搞清楚。有什么想法吗?

    谢谢。

    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 回复  |  直到 14 年前
        1
  •  2
  •   Dimitar Christoff    14 年前

    你能多发点吗?基本上-类的框架以及调用新实例的函数 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();