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

查看:71
本文介绍了将事件侦听器作为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.

推荐答案

您需要

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参数.

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

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

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