简体   繁体   English

如何在第二个参数是闭包的情况下使用 removeEventListener

[英]How use removeEventListener where second parameter is closure

I have我有

getEventNameFromInput() {
    this.inputName.addEventListener('keyup', this.eventName())
}
eventName() {
    let eventName = [];
    return (e) => {
        eventName.push(e.target.value)
           
    }
};

I try to use in second object but doesnt' work.我尝试在第二个 object 中使用,但不起作用。 :

interfaceUser.inputName.removeEventListener('keyup', interfaceUser.eventName())

This and interfaceuser are references the same instance of object.这和 interfaceuser 是引用 object 的同一实例。 getEventNameFromInput and eventName are in object InterfaceUser getEventNameFromInput 和 eventName 在 object InterfaceUser

When you call removeEventListener you have to pass the same function .当您调用removeEventListener时,您必须传递相同的 function

With your existing code, every time you call eventName , it generates a new arrow function and returns that.使用您现有的代码,每次调用eventName时,它都会生成一个新箭头 function 并返回它。 An identical function will not do the job.相同的 function 将无法完成这项工作。 You need the same function.您需要相同的 function。

This means that you need to store the function when you create it, and then retrieve the value from the store next time you need it.这意味着您需要在创建 function 时对其进行存储,然后在下次需要时从存储中检索该值。

For example:例如:

eventName() {
    if (!this.eventHandler) {
        let eventName = []; 
        this.eventHandler = (e) => {
            eventName.push(e.target.value)
        }
    }
    return this.eventHandler;
};

I would suggest to go with custom events as specified here: https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events我建议 go 使用此处指定的自定义事件: https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events

 const form = document.querySelector('form'); const textarea = document.querySelector('textarea'); form.addEventListener('awesome', e => console.log(e.detail.text())); textarea.addEventListener('input', function() { // Create and dispatch/trigger an event on the fly // Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element this.dispatchEvent(new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.value } })) });
 <form> <textarea></textarea> </form>

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

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