Removing event listeners as functions of Class.prototype

I am trying to use classes based on Class.prototype in my project where I have no built-in functions. Given this example, it is not possible to remove the eventListener on the myVideo video myVideo that I have in my class.

This is a theoretical example, not the actual production code that 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 with the Class.prototype function and add and remove listeners. I need to create an instance and create many objects of this type, and I am afraid of memory leaks and persistence of the object (all previously created objects receive the "completed" event), leaving the anonymous functions not deleted as event handlers.

Or should I just consider a different approach (the built-in functions inside the initialize function, like event handlers). They really affect readability and consistency, so I want to avoid them at all costs.

+5
source share
2 answers

You need to bind your onMyVideoEnded function with the context in which you attached it:

For instance:

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

To remove a listener, also use a stored handler:

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

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

+17
source

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 the 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); 
0
source

Source: https://habr.com/ru/post/1401605/


All Articles