TypeScript:删除本地胖箭头的侦听器

时间:2016-07-05 22:25:42

标签: typescript

我想使用本地胖箭头来保存上下文:

document.addEventListener("keydown", (e: KeyboardEvent) => myobject.keyDownlistener(e));

我希望以后能够删除此侦听器,但以下两项工作都没有:

document.removeEventListener("keydown", (e: KeyboardEvent) => myobject.keyDownlistener(e));
document.removeEventListener("keydown", myobject.keyDownlistener);

我该怎么办?

2 个答案:

答案 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