NodeJS のイベント エミッターは通常、Java の静的メソッドのようなものであることに気付きました。例:
// This illustrated that event listener is universal
function A(a){
var that = this;
this.a = a;
this.cnt = 0;
this.done = function(){
this.emit("done");
};
this.say = function(){
console.log(a + " = " + that.cnt);
};
this.inc = function(){
that.cnt++;
};
}
A.prototype = new events.EventEmitter;
var a = new A("a"),
b = new A("b"),
c = new A("c");
a.on("done",function(){a.inc()});
b.on("done",function(){b.inc()});
c.on("done",function(){c.inc()});
c.done();
c.done();
a.say();
b.say();
このコードは次の出力を提供します。
a = 2
b = 2
私が実際に期待している間:
a = 0
b = 0
これは次の行によるものだと思います。
A.prototype = new events.EventEmitter;
「プロトタイプ」の種類の定義は、Java の「静的」のように使用されると思います。
オブジェクトごとのイベント リスナーを使用するために、上記のコードを次のように変更しました。
function B(a){
var that = this;
this.evt = new events.EventEmitter;
this.a = a;
this.cnt = 0;
this.done = function(){
this.evt.emit("done");
};
this.say = function(){
console.log(a + " = " + that.cnt);
};
this.inc = function(){
that.cnt++;
};
}
var a = new B("a"),
b = new B("b"),
c = new B("c");
a.evt.on("done",function(){a.inc()});
b.evt.on("done",function(){b.inc()});
c.evt.on("done",function(){c.inc()});
c.done();
c.done();
a.say();
b.say();
これはオブジェクトごとのイベント リスナーになりますが、EventEmitter の連鎖を壊してしまうため、これは良い設計/実装ではないと思います。つまり、以下のコードのように:
// can chain another method of A after the on() method
a.on("event",functionCallback).anotherMethodOfA();
NodeJS のオブジェクトごとのイベント リスナーの適切な実装は何ですか?