开发者

extending Node.addEventListener method with the same name

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开发者_Python百科 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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜