JavaScript:将事件侦听器移除为Class.prototype函数 [英] JavaScript: removing event listeners as Class.prototype functions

查看:89
本文介绍了JavaScript:将事件侦听器移除为Class.prototype函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的项目中使用基于Class.prototype的类,其中我没有内联函数。考虑到这个例子,我不可能删除我班上的 myVideo 视频对象中的eventListener。

I'm trying to have a Class.prototype based classes in my project, where I don't have inline functions. Considering this example, it's impossible to remove the eventListener on myVideo video object, that I have in my class.

这是一个理论示例,而不是我的实际生产代码。

var myClass = function () {
    this.initialize();
}

MyClass.prototype.myVideo = null;

MyClass.prototype.initialize = function () {
    this.myVideo = document.getElementById("myVideo");
    this.myVideo.addEventListener("ended", this.onMyVideoEnded, false);
    this.myVideo.play();
}

MyClass.prototype.onMyVideoEnded = function (event) {
    // cannot remove event listener here
    // this.myVideo.removeEventListener("ended", this.onMyVideoEnded, false);
}

有没有办法将处理程序保留为Class.prototype函数并添加并删除侦听器。我需要实例化并创建这种类型的很多对象,并且害怕内存泄漏和对象持久性(所有先前创建的对象都会收到已结束事件),而不会将匿名函数作为事件处理程序删除。

Is there a way to leave the handler as a Class.prototype function and add and remove listeners. I need to instantiate and create a lot of objects of this sort, and am afraid of memory leaks, and object persistancy (all of previously created objects receive the "ended" event) when leaving anonymous functions not removed as event handlers.

或者我应该考虑一种不同的方法(内联函数,在initialize函数中,作为事件处理程序)。这些确实影响了可读性和一致性,所以我想在所有成本上避免它们。

Or should I just consider a different approach (inline functions, inside the initialize function, as event handlers). These really impact readability and consistency, so I want to avoid them on all costs.

推荐答案

你需要绑定您的函数 onMyVideoEnded with你附加它的上下文:

You need to bind your function onMyVideoEnded with context where you attached it:

例如:

this.myVideoEndedHandler = this.onMyVideoEnded.bind(this);
this.myVideo.addEventListener("ended", this.myVideoEndedHandler, false);

要删除监听器,还要使用存储的处理程序:

To remove listener also use stored handler:

this.myVideo.removeEventListener("ended", this.myVideoEndedHandler, false);

这是因为当事件触发你的函数 onMyVideoEnded 出错参数。

This is because when event triggers your function onMyVideoEnded gets wrong this argument.

这篇关于JavaScript:将事件侦听器移除为Class.prototype函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆