2010-08-12 47 views
1

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

但是,当我使用.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 
    }); 
}) 

回答

2

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

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

这可能是waaay关闭从你正在尝试做的,但它可能给你一些想法 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();