2

我有两个班级:EventEmitterEventCatcher。有EventCatcher2 个成员EventEmitterEventEmitter 发出一个测试事件。在捕手中,我想捕获所有测试事件并做一些事情:

事件发射器

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');
}

事件捕捉器

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 事件附加到 中的EventCatcherattachHandler,而不必为每个EventEmitter 类手动附加?

4

1 回答 1

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();
    });
};

这篇写的是头脑,所以我真的不知道回调内的范围是否正确。

于 2013-06-28T10:02:10.363 回答