1

我有一个具有此功能的事件/侦听器管理器:

  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 中完成此任务的最佳方式吗?有没有更优雅的方法来实现这个监听器事件触发的优先级列表?

4

1 回答 1

0

也许它比我的更好。但这是一种特定的方式,我的意思是你必须在块中插入新的处理程序。这是一个更通用的工具,但它似乎适用于您的案例。

我建议这样做:

//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);
于 2012-05-31T18:37:09.260 回答