通过javascript中的引用来定义事件处理程序

时间:2014-10-07 12:23:46

标签: javascript

我想从一个类中调用一个类函数,我以前将它附加到一个驻留在类中的按钮对象(以下代码可以工作,但是callMyClassFunction中的作用域是on按钮,我希望它是Carousel ):

//Examplecode 1
Carousel.prototype.addEventListeners = function(){
    this.button.on('click', this.callMyClassFunction);
}

Carousel.prototype.callMyClassFunction = function(){
    console.log(this);
}

如果我将函数绑定为它的工作原理(其范围是类实例):

//Examplecode 2
Carousel.prototype.addEventListeners = function(){
    this.button.on('click', function(){
        this.callMyClassFunction()
    }).bind(this);
}

但我宁愿添加一个带引用的click-eventlistener(比如在Examplecode 1中),因为我想在另一个函数中调用removeListener:

//Examplecode 3
Carousel.prototype.removeEventListeners = function(condition){
    if(condition){
        this.button.removeListener('click', this.callMyClassFunction);
    }
}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

您可以更简单地使用bind

Carousel.prototype.addEventListeners = function(){
    this.button.on('click', this.callMyClassFunction.bind(this));
};

我不确定您在示例中使用了哪些bind(您是在on函数的返回值上调用它),但上面使用了Function#bind ,这是JavaScript本身的一部分(从ES5开始;对于旧浏览器来说,它很容易填充/填充)。 Function#bind返回一个新函数,该函数在调用时调用原始函数,并将this设置为您给出的第一个参数bind。因此,在上文中,点击将调用bind返回的函数,该函数会调用callMyClassFunction并将this设置为正确的值。

如果您稍后需要使用removeListener并且需要将相同的功能传递给它,那么您必须记住该功能,如下所示:

Carousel.prototype.addEventListeners = function(){
    if (!this.boundCallMyClassFunction) {
        this.boundCallMyClassFunction = this.callMyClassFunction.bind(this);
    }
    this.button.on('click', this.boundCallMyClassFunction);
};

Carousel.prototype.removeEventListeners = function(condition){
    if(condition && this.boundCallMyClassFunction){
        this.button.removeListener('click', this.boundCallMyClassFunction);
    }
};

你不能再次传递调用bind的结果,因为这将是一个不同的功能。

但请查看提供您上面调用的onremoveListener函数的文档,它可能提供了一种更简单的方法(jQuery可以,但它并不像你在那里使用jQuery那样。)

答案 1 :(得分:1)

只需将绑定的侦听器存储在您的实例上:

functin Carousel(…) {
    …
    this.callMyClassFunction = this.callMyClassFunction.bind(this);
}
Carousel.prototype.callMyClassFunction = function(){
    console.log(this);
};
Carousel.prototype.addEventListeners = function(){
    this.button.on('click', this.callMyClassFunction);
};
Carousel.prototype.removeEventListeners = function(…){
    …
    this.button.removeListener('click', this.callMyClassFunction);
};