Node.js EventEmitter如何为多个事件绑定同一个处理函数
方案1:原生无侵入实现(推荐)
直接把要绑定的事件名放入数组,通过遍历完成批量绑定,不需要修改内置对象,兼容性最好:
const { EventEmitter } = require("events"); const emitter = new EventEmitter(); const handler = () => console.log("the devil"); // 批量绑定 ["runninwith", "sympathyfor", "shoutat"].forEach(evt => emitter.on(evt, handler)); // 测试触发 emitter.emit("runninwith"); emitter.emit("sympathyfor");
方案2:扩展EventEmitter实现数组参数写法
如果你需要频繁使用多事件绑定同一个处理函数的逻辑,可以给EventEmitter扩展自定义方法,完全实现你想要的调用形式:
const { EventEmitter } = require("events"); // 扩展多事件绑定方法 EventEmitter.prototype.onMany = function (eventList, handler) { eventList.forEach(evt => this.on(evt, handler)); return this; // 支持链式调用 }; const emitter = new EventEmitter(); const handler = () => console.log("the devil"); // 调用形式和你预期的几乎完全一致 emitter.onMany(["runninwith", "sympathyfor", "shoutat"], handler); // 测试触发 emitter.emit("runninwith"); emitter.emit("shoutat");
两种方案都可以完全替代你原有重复调用emitter.on的写法,实现多事件触发同一个处理函数的需求。
内容的提问来源于stack exchange,提问作者Behemoth
相关产品推荐
相关产品推荐

