gpt4 book ai didi

javascript - 删除事件监听器作为 Class.prototype 函数

转载 作者:数据小太阳 更新时间:2023-10-29 05:43:38 35 4
gpt4 key购买 nike

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

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

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 函数并添加和删除监听器。我需要实例化和创建很多此类对象,并且担心内存泄漏和对象持久性(所有以前创建的对象都会收到“结束”事件),因为匿名函数不会作为事件处理程序被删除。

或者我应该考虑一种不同的方法(内联函数,在初始化函数内部,作为事件处理程序)。这些确实会影响可读性和一致性,因此我想不惜一切代价避免它们。

最佳答案

您需要bind您的函数 onMyVideoEnded 以及您附加它的上下文:

例如:

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

要删除监听器也可以使用存储的处理程序:

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

这是因为当事件触发你的函数时 onMyVideoEnded 得到了错误的 this 参数。

关于javascript - 删除事件监听器作为 Class.prototype 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9720927/

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