我想使用本地胖箭头来保存此上下文:
document.addEventListener("keydown", (e: KeyboardEvent) => myobject.keyDownlistener(e));
我希望以后能够删除此侦听器,但以下两项工作都没有:
document.removeEventListener("keydown", (e: KeyboardEvent) => myobject.keyDownlistener(e));
document.removeEventListener("keydown", myobject.keyDownlistener);
我该怎么办?
答案 0 :(得分:4)
稍后删除此侦听器,但以下两项都不起作用:
每次创建()=>
时,都会创建一个新功能。因此,您需要确保添加并删除 相同的功能:
// What you add
document.addEventListener("keydown", myobject.keyDownlistener);
// Is what you should remove
document.removeEventListener("keydown", myobject.keyDownlistener);
要保留this
上下文,请确保将myobject.keyDownlistener
定义为胖箭头(而不是原型函数)
https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
答案 1 :(得分:0)
您可以将对内联函数的引用保存到变量(或本示例中所示的对象属性),然后将其传递给对addEventListener的调用
var myobject = {
keyDownlistener: function (e) {
if (e.key==="Enter") {
console.log('you typed',this.msg);
document.removeEventListener("keydown", myobject.kdl);
}
if (!this.msg) this.msg='';
this.msg += e.key;
}
};
document.addEventListener("keydown", myobject.kdl = (e) => myobject.keyDownlistener(e));

Click here then type a message followed by enter

如果您对使用外部变量感到满意:
var kd,myobject = {
keyDownlistener: function (e) {
if (e.key==="Enter") {
console.log('you typed',this.msg);
document.removeEventListener("keydown",kd);
}
if (!this.msg) this.msg='';
this.msg += e.key;
}
};
document.addEventListener("keydown", kd = (e) => myobject.keyDownlistener(e));

click here and type a line of text