Removing event listeners as Class.prototype functions

杀马特。学长 韩版系。学妹 提交于 2019-12-18 16:58:38

问题


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.

This is a theoretical example, not an actual production code I have.

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);
}

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.

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.


回答1:


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

For example:

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);

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




回答2:


i use this:

this.element.handler = handler.bind(this);
this.element.removeEventListener('event', this.element.handler, false);
this.element.addEventListener('event', this.element.handler, false);

or use a WeakMap object:

var handlers = new WeakMap();
var self = this;
handlers.set(this.element, { handler: handler.bind(self) });
var handler = handlers.get(this.element).handler;
this.element.removeEventListener('event', handler, false);
this.element.addEventListener('event', handler, false);


来源:https://stackoverflow.com/questions/9720927/removing-event-listeners-as-class-prototype-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!