我也不建议重写该addEventListener
方法。但我也认为,自己尝试某些事情来测试,看看是否存在某些问题以及在哪里存在问题,这也不错。所以无论如何,这里有一个关于如何做到这一点的想法:
var f = Element.prototype.addEventListener;
Element.prototype.addEventListener = function(type, func, x){
var that = this;
if (that.evts === undefined) {
that.evts = {};
}
if (that.evts[type] === undefined) {
that.evts[type] = [];
f.call(that, type, function(){
for (var i = 0; i < that.evts[type].length; i++) {
that.evts[type][i].apply(that, arguments);
}
}, x);
}
that.evts[type].push(func);
};
我不是百分百确信我没有错过任何东西,但理论上这应该以某种方式覆盖该方法,即添加事件侦听器的顺序应该与执行处理程序的顺序相同。
这是通过在每次addEventListener
调用方法时将处理函数保存在一个数组中来完成的,并且只添加一个遍历该数组并执行其中的每个函数的事件侦听器。
Of course you would also have to change the removeEventListener
method to remove the items in your array. And you would have to do the same for Document.prototype.addEventListener
and Window.prototype.addEventListener
.
FIDDLE
Note that I added a property called evts
(which contains the function arrays) to the element to which the listener was added. This is probably not the best way to do it, since anyone can override that property. It probably would be better to store your arrays somewhere in a local variable or at least rename it to something that is unlikely to be overridden by accident.