I’m trying to extend the Node.addEventListener method so I can do some events management like:
Node.prototype.on = function (type, listener, useCapture) {
'use strict';
var i, evt;
this.events = this.events || [];
for (i = 0; i < this.events.length; i += 1) {
evt = this.events[i];
if (this === evt[0] && type === evt[1]) {
this.removeEventListener(type, evt[2], evt[3]);
this.events.splice(i, 1);
}
}
this.events.push([this, type, listener, useCapture]);
return this.addEventListener(type, listener, useCapture);
};
But in this case, instead of naming it on I would like to name it the same addEventListener so I can guarantee any javascript will work on it.
So the point here is that if I name the function as addEventListener instead on on the return clause it will cause an endless loop. so I was thinking if is there any way to make it call the super method instead?
Thanks in advance
First of all let me point out again (for other readers), that extending the DOM is a bad idea in general.
That said, here is what you could do, if the environment lets you:
You can keep a reference to the original
addEventListenerfunction and call it with.call.This only works if
addEventListenerexposes this method (i.e. is like a native JavaScript function) and you can actually overwriteaddEventListener:Notice that
addEventListeneris a method of theElementinterface, not theNodeinterface.Again: This is not guaranteed to work, and even if it works now, it might break in the future.