register and fire events with promises returns without EventEmmiter
npm install he-event-systemplease be careful when upgrading.
npm install he-event-system --save@notice all paths must be relative to the root path of the project
first you should define an Event class like this
./path/to/Event.js
class Event {
/**
* @desc the event class is a holder to all information that listeners need to accomplish thier tasks
* and may be contain any required methods or params.
* @param {Array
*/
constructor(arg1, arg2, arg3) {
// any setup for the event
this.args = args;
}
}
module.exports = Event;
then you should define at least one Listener Class to this event
./path/to/listener.js
class Listener {
/**
* any pre setup before running handler()
*/
constructor() {}
/**
* @desc the main method that hold logic for the listener, it may be
* contain any methods or proberties that needed.
* @param {Object} event [the event Instance of the Event class]
* @return {Promise
*/
handler(event) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('hello from listener one');
});
/**
* here we called resolve outside the setTimeout
* so the listener will run Async
* if we need the listeners to run in order, just change
* the place of resolve() and put it inside the Async operation.
*/
resolve();
});
}
}
module.exports = Listener;
finally we start creating the Dispatcher Instance
const DispatcherCore = require('he-event-system');
const EventsListeners = [
"./path/to/Event": [
"./path/to/listener1",
"./path/to/listener2",
...
],
"./path/to/Event2": [
"./path/to/listener1",
"./path/to/listener2",
...
]
];
/**
* create new instance of DispatcherCore
* @param {Object} EventsListeners [optional -> you can pass object contains all your events and listeners instead of passing them individually]
*/
const Dispatcher = new DispatcherCore(EventsListeners);
add more than listener at once
Dispatcher.addListeners('./path/to/event', [
'./path/to/listener1',
'./path/to/listener2'
]);
add listeners one by oneDispatcher.addListener('./path/to/event', './path/to/listener');
remove one listenerDispatcher.removeListener('./path/to/event', './path/to/listener');
remove all listeners.Dispatcher.removeListeners('./path/to/event');
alias for removeListeners()Dispatcher.stop('./path/to/event');
grab all listenersDispatcher.getListeners('./path/to/event');
get the number of listeners for an eventDispatcher.countListeners('./path/to/event');
Dispatcher.fire('./path/to/event', 'argOne', 'argTwo', 'argThree').then((data) => {
console.log('success -> ' + data);
}, (err) => {
console.log('err -> ' + err);
});
the main object that contains all events with listenersDispatcher.events;
I'm Welcoming with any comment or advise or you can open new issue on github
1. add Support for Logging and Logging Level (errors, warnings, successes)