gpt4 book ai didi

javascript - 将事件监听器附加到类以监听来自其成员的事件

转载 作者:行者123 更新时间:2023-11-30 06:41:41 25 4
gpt4 key购买 nike

我有两个类:EventEmitterEventCatcherEventCatcher 有 2 个 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');
}

事件捕捉器

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 类手动附加?

最佳答案

是这样的吗?

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

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

关于javascript - 将事件监听器附加到类以监听来自其成员的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10758596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com