gpt4 book ai didi

javascript - 删除事件监听器 vanilla JS

转载 作者:行者123 更新时间:2023-11-28 19:04:33 26 4
gpt4 key购买 nike

我在这支笔中描述了一个尽可能简短的特殊场景:http://codepen.io/tuelsch/pen/rVRRNm?editors=101

这篇文章 ( Adding and Removing Event Listeners with parameters ) 为我指明了正确的方向,但有不同的设置。

我喜欢有一个自定义 JS 对象(Film),它可以在其 link 属性(DOM 元素)上添加和删除事件处理程序。

我被第 18 行的 removeEvent 函数困住了。在这种情况下,removeEventListener 函数的第二个参数正确是什么?

它没有添加和删除事件监听器,而是不断添加事件监听器,如在控制台中观察到的,其中记录了第 8 行的结果。

该解决方案应该是普通的 JavaScript、ES5 兼容并且旨在在浏览器 (IE9+) 中运行。

最佳答案

  1. 您可以首先在对象中保留该绑定(bind)事件的记录,例如:
// Add the event handler
Film.prototype.bindEvent = function () {
// This ensure that the binded event can be removed by removeEvent
// even if you call bindEvent many times.
if (!this._bindedEvent) {
this._bindedEvent = this.eventHandler.bind(this);
this.link.addEventListener('click', this._bindedEvent);
}
}

然后删除它:

// Remove the event handler
Film.prototype.removeEvent = function () {
if (this._bindedEvent) {
this.link.removeEventListener('click', this._bindedEvent);
this._bindedEvent = null;
}
}

2.另一种方法是在构造函数中重写eventhandler:

// The test class definition
var Film = function () {
this.link = document.getElementById('film');
// This first find if self has attr eventHandler, and keep lookup to its prototype.
// Then createa binded version of eventhandler and set to this's attr.
// So when you try to access `this.eventHandler`, it'll be the binded version instead of Prototype's
this.eventHandler = this.eventHandler.bind(this);
}

然后你就可以使用

// Add the event handler
Film.prototype.bindEvent = function () {
this.link.addEventListener('click', this.eventHandler);
}

// Remove the event handler
Film.prototype.removeEvent = function () {
this.link.removeEventListener('click', this.eventHandler);
}

添加和删除它。

关于javascript - 删除事件监听器 vanilla JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31942959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com