我有一个具有此功能的事件/监听器管理器:
var addListener = function(event, listener) {
myListeners[event].push(listener); //assume this code works
}
但现在我需要更改它,使其看起来像这样:
var addListener = function(event, listener, fireFirst) {
if(fireFirst) {
myListenersToFireFirst[event].push(listener);
} else {
myListenersToFireSecond[event].push(listener);
}
}
这样,当调用 fireEvent
函数时,它将首先触发 myListenersToFireFirst
数组中的监听器,然后触发第二个数组中的监听器。
所以它看起来像这样:
var fireEvent = function(event) {
var firstListeners = myListenersToFireFirst[event];
//for each listener in firstListeners, call `apply` on it
var secondListeners = myListenersToFireSecond[event];
//for each listener in secondListeners, call `apply` on it
}
这是在 JavaScript 中实现此目的的最佳方法吗?是否有更优雅的方法来实现监听器事件触发的优先级列表?
最佳答案
也许它是比我的更好的方法..但这是一种特定的方法,我的意思是你必须在 block 中插入新的处理程序。这是一个更通用的工具,但它似乎适用于您的案例。
我建议这样做:
//makes a closured function that calls this function after the other
Function.prototype.prefix=function(o) {
var that=this;
return function(){
that.apply(this,arguments);
return o.apply(this,arguments);
};
}
//prefix=reversed sufix
Function.prototype.sufix=function(o) {return o.prefix(this);}
使用此代码,您可以将函数相互附加/前置以形成一种链,这对于添加另一个监听器或跟踪函数的使用很有用,甚至可以在影响最小的情况下调整代码。
一些用法
function audit() {console.log(arguments.callee.caller,arguments.callee.name,arguments);}
function a() {alert(arguments);}
a=audit.prefix(a);
//a user function
function f() {alert(arguments);}
f("test");//just do the alert as defined
f=audit.prefix(a);
f("test");//now arguments will be on console too
//a builtin function
//this audit example only write to the console the arguments being passed to it
function audit() {console.log(arguments.callee,arguments);}
//auditing alert function (not too usefull, but shows it works even for
alert=audit.prefix(alert);//alert is now prefixed with audit
//an event handler
document.body.onclick=function() {alert("clicked");};
document.body.onclick=audit.prefix(document.body.onclick);
关于javascript - 如何在 JavaScript 中实现简单的优先监听器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10839146/