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最初に配列内のリスナーを起動し、次に 2 番目の配列内のリスナーを起動するようにするためです。

したがって、次のようになります。

  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 に答える