0

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 のオブジェクトごとのイベント リスナーの適切な実装は何ですか?

4

1 に答える 1

0

addListenerまたはを使用onして、リスナーをカスタム イベントにアタッチできます。これらのメソッドの呼び出しをチェーンする必要はありません。もちろん、任意のオブジェクトを継承し、オブジェクトEventEmitterに放出機能を追加できます。のインスタンスからオブジェクトを継承できますEventEmitter。あなたのためにそれを行うライブラリで呼び出さinheritれる関数があります。util

var util = require('util');
var eventEmitter = require('events').EventEmitter;

// Now create your constructor/object.
function MyObj(a, b) {
    this.a = a;
    this.b = b;
    .
    .
    .
}
util.inherits(MyObj,eventEmitter);

// Implement your methods and add the functionality you need.
MyObj.prototype.aMethod = function(arg) {
    .
    .
    .
    // Define how to emit events
    if (arg == 'A')
        this.emit('eventA', this.a);
    else if (arg == 'B')
        this.emit('eventB');

    // Return this for chaining method calls
    return this;
}

MyObj.prototype.anotherMethod = function() {
    // Add more functionality...
    .
    .
    .
    return this;
}

// Now instantiate the constructor and add listenters

var instanceOfMyObj = new MyObj('a parameter', 'another parameter');

instanceOfMyObj.on('eventA', function(a){
    // Handle the event
});

// Now chain calls..
instanceOfMyObj.aMethod('A').anotherMethod(); // This will trigger eventA...
于 2013-05-29T06:21:09.950 に答える