1

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

zanona
  • 12,345
  • 25
  • 86
  • 141
  • Before you go any further, please read [What’s wrong with extending the DOM](http://perfectionkills.com/whats-wrong-with-extending-the-dom). – Felix Kling Aug 28 '11 at 11:01
  • thanks for the tip Felix, actually I was aware of this article, but as this is only supposed to run on a very closed and private environment I've concluded that it won't be a problem on my case. but thanks again for showing me this. :) – zanona Aug 28 '11 at 11:05
  • Ok :) The article also mentions that it is probably ok to do this in a closed environment... just wanted to make sure that you are aware of this ;) – Felix Kling Aug 28 '11 at 11:09

1 Answers1

5

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 addEventListener function and call it with .call.
This only works if addEventListener exposes this method (i.e. is like a native JavaScript function) and you can actually overwrite addEventListener:

// immediate function to create scope
(function() {
    // keep a reference to the original method
    var orig_addEventListener = Element.prototype.addEventListener;

    Element.prototype.addEventListener = function (type, listener, useCapture) {
        // your code here
        //...
        // call the original method
        return orig_addEventListener.call(this, type, listener, useCapture);  
    };

}());

Notice that addEventListener is a method of the Element interface, not the Node interface.

Again: This is not guaranteed to work, and even if it works now, it might break in the future.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143