扫码关注官方订阅号
认证0级讲师
const something = { bindEvent() { // 不管是用 function 或箭头函数封装还是 bind(this), // 都会产生新的函数,需要把这个新函数保存起来,这里用 this.events 来保存, // 方便以后移除绑定事件 this.events = { mouseenter: e => this.mouseenterHandler(e), mouseleave: this.mouseleaveHandler.bind(this), click: this.clickHandler }; // Array.from 可以把伪数组变成真正的数组, // 当然原来的 [].forEach.call 也没有什么问题 // 不过 dot => { ... } 是箭头函数,不需要定义 self 来保存 this Array.from(document.querySelectorAll(".dot")) .forEach(dot => { // 这里是三句 addEventListener, // 直接用 Object.keys(this.events).forEach 简写了 Object.keys(this.events) .forEach(key => dot.addEventListener(key, this.events[key])); }); }, unbindEvent() { // 万一没调 bindEvent,this.events 会是 undefined,所以这里处理一下。 // 其它的和 bindEvent 中的代码差不多,就不逐一解释了 const events = this.events || {}; Array.from(document.querySelectorAll(".dot")) .forEach(dot => { Object.keys(events) .forEach(key => dot.removeEventListener(key, events[key])); }); } };
在 bindEvent() 中,mouseenter 绑定是事件处理函数是 function(e) {self.mouseenterHandler(e)},而不是 this.mouseenterHandler,因此你的 unbindEvent() 是问题的。
bindEvent()
mouseenter
function(e) {self.mouseenterHandler(e)}
this.mouseenterHandler
unbindEvent()
function是同一个引用就行吧,你这看起来就clickHandler移除了
你的绑定是匿名函数,自然解绑就是找不到的。
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
在
bindEvent()中,mouseenter绑定是事件处理函数是function(e) {self.mouseenterHandler(e)},而不是this.mouseenterHandler,因此你的unbindEvent()是问题的。function是同一个引用就行吧,你这看起来就clickHandler移除了
你的绑定是匿名函数,自然解绑就是找不到的。