删除通过绑定添加的事件侦听器

编程入门 行业动态 更新时间:2024-10-17 05:35:15
本文介绍了删除通过绑定添加的事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 JavaScript 中,使用 bind() 删除作为事件侦听器添加的函数的最佳方法是什么?

In JavaScript, what is the best way to remove a function added as an event listener using bind()?

示例

(function(){ // constructor MyClass = function() { this.myButton = document.getElementById("myButtonID"); this.myButton.addEventListener("click", this.clickListener.bind(this)); }; MyClass.prototype.clickListener = function(event) { console.log(this); // must be MyClass }; // public method MyClass.prototype.disableButton = function() { this.myButton.removeEventListener("click", ___________); }; })();

我能想到的唯一方法是跟踪每个添加了 bind 的监听器.

The only way I can think of is to keep track of every listener added with bind.

上面这个方法的例子:

(function(){ // constructor MyClass = function() { this.myButton = document.getElementById("myButtonID"); this.clickListenerBind = this.clickListener.bind(this); this.myButton.addEventListener("click", this.clickListenerBind); }; MyClass.prototype.clickListener = function(event) { console.log(this); // must be MyClass }; // public method MyClass.prototype.disableButton = function() { this.myButton.removeEventListener("click", this.clickListenerBind); }; })();

有没有更好的方法来做到这一点?

Are there any better ways to do this?

推荐答案

虽然@machineghost 说的是对的,但事件的添加和删除方式相同,但等式中缺失的部分是:

Although what @machineghost said was true, that events are added and removed the same way, the missing part of the equation was this:

.bind() 被调用后会创建一个新的函数引用.

A new function reference is created after .bind() is called.

参见绑定()更改函数引用?|如何永久设置?

因此,要添加或删除它,请将引用分配给变量:

So, to add or remove it, assign the reference to a variable:

var x = this.myListener.bind(this); Toolbox.addListener(window, 'scroll', x); Toolbox.removeListener(window, 'scroll', x);

这对我来说按预期工作.

This works as expected for me.

更多推荐

删除通过绑定添加的事件侦听器

本文发布于:2023-11-27 22:00:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639758.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:侦听器   绑定   事件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!