Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing event listeners as Class.prototype functions

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.

like image 710
joncys Avatar asked Mar 15 '12 13:03

joncys


2 Answers

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.

like image 196
antyrat Avatar answered Oct 12 '22 14:10

antyrat


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);
like image 44
Darío Gómez Fisicaro Avatar answered Oct 12 '22 13:10

Darío Gómez Fisicaro