简体   繁体   English

如何在初始化函数中将原型函数添加到事件侦听器?

[英]How can I add a prototype function to an event listener in the initialization function?

I'm not sure exactly how to phrase my question, so let me present an example: 我不确定如何说出我的问题,所以让我举一个例子:

function foo() {
  window.addEventListener("keydown", function(event) {
        bar(event.keycode);
}

foo.prototype.bar = function (keycode) {
//code
}

I've tried using this.bar() , but that results in using the window as this . 我已经尝试使用this.bar()但是这导致使用该window作为this Is there a way to do this, or will I have to call another initialize method manually? 有没有办法做到这一点,还是我必须手动调用另一个初始化方法?

Bind this.bar to this before you pass it. 在传递之前将this.bar绑定this

function foo() {
    window.addEventListener("keydown", this.bar.bind(this), false);
}


foo.prototype.bar = function (event) {
    console.log(event.keyCode);
}

demo http://jsfiddle.net/2tee4/ 演示http://jsfiddle.net/2tee4/

An alternative solution if you don't have Function.prototype.bind available*, and you're unwilling to add extra functions to Function.prototype would be to close over the call to this.bar : 如果你没有Function.prototype.bind可用的替代解决方案*,并且你不愿意向Function.prototype添加额外的函数将关闭对this.bar

function foo() {
    var self;
    self = this;
    window.addEventListener('keydown', function (e) {
        self.bar(e);
    }, false);
}
foo.prototype.bar = function (e) {
    console.log(e.keyCode);
}

* although your use of addEventListener without attachEvent leads me to believe that Function.prototype.bind would be an acceptable choice *尽管你使用不带attachEventaddEventListener让我相信Function.prototype.bind是一个可以接受的选择


Additionally, libraries such as jQuery may include their own form of bind , jQuery's is jQuery.proxy . 另外,诸如jQuery库可能包含它们自己的bind形式,jQuery是jQuery.proxy

If your intention is to add a new listener for every foo created, another option is to make foo implement the EventListener interface, and simply pass this in place of the handler. 如果你的目的是为每个创建的foo添加一个新的监听器,另一个选择是使foo实现EventListener接口,并简单地传递this来代替处理程序。

function Foo() {
    window.addEventListener("keydown", this, false);
}

Foo.prototype.bar = "foobar";

Foo.prototype.handleEvent = function(e) {
    console.log(e.type);   // "mousedown" (for example)
    console.log(this.bar); // "foobar"
};

new Foo();

Note that this only works with addEventListener() . 请注意,这仅适用于addEventListener()

DEMO: http://jsfiddle.net/k93Pr/ 演示: http //jsfiddle.net/k93Pr/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM