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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With