记一次使用 removeEventListener 移除事件监听失败的经历
生活随笔
收集整理的這篇文章主要介紹了
记一次使用 removeEventListener 移除事件监听失败的经历
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
測試一
測試代碼如下
var Test = function() {this.element = document.body;this.handler = function() {console.log(this);};this.element.addEventListener('click', this.handler.bind(this), false);this.destroy = function() {this.element.removeEventListener('click', this.handler, false);}; }; var test = new Test();但是,測試結(jié)果發(fā)現(xiàn),調(diào)用 test.destroy() 后,點擊依舊有效。明明按照以前看的文檔說的,add 和 remove 的時候是同一個函數(shù)啊。
測試二
于是,又調(diào)整了一下代碼。
var Test = function() {this.element = document.body;this.handler = function() {console.log(this);};this.element.addEventListener('click', this.handler, false);this.destroy = function() {this.element.removeEventListener('click', this.handler, false);}; };去掉了 add 時的 bind,再測試發(fā)現(xiàn)點擊不響應(yīng)了。
結(jié)論
經(jīng)過測試,add 和 remove 事件監(jiān)聽回調(diào)時,既不能使用匿名函數(shù),也不能改變指定函數(shù)的上下文。
轉(zhuǎn)載于:https://www.cnblogs.com/xiaoyucoding/p/8516407.html
總結(jié)
以上是生活随笔為你收集整理的记一次使用 removeEventListener 移除事件监听失败的经历的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 百度API地图的标注不居中显示,而显示在
- 下一篇: Windows 任务管理器中的几个内存概