将事件侦听器附加到类以侦听其成员的事件

时间:2012-05-25 17:07:16

标签: javascript events node.js javascript-events

我有两个类: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 个答案:

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

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