2012-05-25 86 views
2

我有2個類:EventEmitter和EventCatcher。 EventCatcher有2個EventEmitter成員。 EventEmitter發出測試事件。在捕手我要趕所有的測試活動,並做一些事情:將一個事件監聽器附加到一個類來監聽其成員的事件

EventEmitter

var events = require('events'); 
var sys = require('util'); 

module.exports = eventEmit; 

function eventEmit(name) { 
    this.name = name; 
    events.EventEmitter.call(this); 
} 

sys.inherits(eventEmit, events.EventEmitter); 

eventEmit.prototype.emitTest = function() { 
    var self = this; 
    self.emit('test'); 
} 

EventCatcher

var eventEmit = require('./eventEmit'); 

module.exports = eventCatch; 

function eventCatch() { 
    this.eventEmitA = new eventEmit("a"); 
    this.eventEmitB = new eventEmit("b"); 
    this.attachHandler(); 
} 

eventCatch.prototype.attachHandler = function() { 
    //I want to do something like: 
    // this.on('test', function() }; 

    this.eventEmitA.on('test', function() { 
     console.log("Event thrown from:\n" + this.name); 
    }); 
    this.eventEmitB.on('test', function() { 
     console.log("Event thrown from:\n" + this.name); 
    }); 
}; 

eventCatch.prototype.throwEvents = function() { 
    var self = this; 
    self.eventEmitA.emitTest(); 
    self.eventEmitB.emitTest(); 
}; 

有沒有辦法附加X事件在attachHandler的EventCatcher類,不必須手動附加每個EventEmitter類?

+1

在你的問題中沒有問號。如果你正在尋找更好的方法來實現這一點,你可能會想在[codereview.stackexchange.com](http://codereview.stackexchange.com/)上發佈這個。 –

+0

沒有更好的辦法,這是捕捉事件的唯一途徑。 –

回答

0

是這樣的嗎?

var eventEmit = require('./eventEmit'); 

module.exports = eventCatch; 

function eventCatch() { 
    this.emitters = []; 
    this.emitters.push(new eventEmit("a")); 
    this.emitters.push(new eventEmit("b")); 
    this.on('test', function() { 
     console.log("Event thrown from:\n" + this.name); 
    }); 
} 

eventCatch.prototype.on = function(eventName, cb) { 
    this.emitters.forEach(function(emitter) { 
     emitter.on(eventName, cb); 
    }); 
}; 

eventCatch.prototype.throwEvents = function() { 
    this.emitters.forEach(function(emitter) { 
     emitter.emitTest(); 
    }); 
}; 

這寫的是從頭腦,所以我真的不知道範圍內的回調是否正確。