evtutil
v1.0.0
Published
Event Chooser evtutil is a utility package that allows you to set up a selection of listeners for an EventEmitter. When one of the specified events occurs, the associated listener is executed, and all other listeners are removed.
Downloads
6
Readme
Event Chooser evtutil is a utility package that allows you to set up a selection of listeners for an EventEmitter. When one of the specified events occurs, the associated listener is executed, and all other listeners are removed.
Installation You can install the package using npm:
npm install evtutil
Usage
To use the package, import the choose function and pass an EventEmitter instance along with an object that maps event names to their corresponding callback functions.
Example
const EventEmitter = require('events');
const { choose } = require('evtutil');
// Create a new EventEmitter instance
const evt = new EventEmitter();
// Define event listeners
const listeners = {
'eventA': (data) => console.log('Event A triggered with data:', data),
'eventB': (data) => console.log('Event B triggered with data:', data),
};
// Use the choose function to attach listeners
choose(evt, listeners);
// Emit one of the events
evt.emit('eventA', 'Hello, Event A!'); // This will trigger the 'eventA' listener and remove both 'eventA' and 'eventB' listeners
How it works
choose takes two arguments:
evt: An instance of EventEmitter. listenArr: An object where each key is an event name and the corresponding value is the function to be executed when that event occurs. Each event listener is registered using evt.once(), so it only fires once.
Once an event is triggered, the corresponding function is executed and all listeners specified in listenArr are removed from evt.
Parameters
evt: EventEmitter: The instance of EventEmitter that will emit the events. listenArr: { [key: string]: Function }: An object containing key-value pairs, where the key is the event name and the value is the function to be executed when the event is emitted. Example Usage This utility is useful when you have multiple events that could occur, but you only want one of them to trigger its associated logic. Once one event occurs, the rest are ignored.
工作原理
choose 接受两个参数:
evt: 一个 EventEmitter 实例。 listenArr: 一个对象,其中每个键是事件名称,对应的值是事件发生时要执行的函数。 每个事件监听器使用 evt.once() 注册,因此它只会触发一次。
一旦某个事件被触发,关联的函数将执行,并且 listenArr 中指定的 所有 监听器都会从 evt 中移除。 在事件处理完成后,确保所有不再需要的事件监听器(如 error 事件监听器)被移除。
参数说明
evt: EventEmitter: 事件发射器的实例。 listenArr: { [key: string]: Function }: 包含键值对的对象,键为事件名称,值为事件触发时要执行的函数。 示例用法 当你有多个可能发生的事件时,此实用工具非常有用,但你只想让其中一个事件触发其关联的逻辑。一旦一个事件发生,其余的事件将被忽略。
许可证 MIT