Event Hub(bus) implemented in JavaScript
Install the version you want by navigating to the relase tab and choosing the one you want
or
Install the latest version
npm install norzon/eventhub.js
If you plan on compiling to an earlier version of JS, such as ES5, or you don't care about compatibility then use:
node_modules/eventhub.js/lib/eventhub.js
On the other hand, if you care about compatibility and are not planning on compiling to ES5 or similar, use:
node_modules/eventhub.js/dist/eventhub.js
(or)
node_modules/eventhub.js/dist/eventhub.min.js
For TypeScript users, the declaration file can be found at:
node_modules/eventhub.js/lib/eventhub.d.ts
The eventhub.js library declares an "EventHub" class, therefore you can have many eventhub instances where each one has seperate event listeners and handlers.
To initialize an EventHub object, use:
const eventhub = new EventHub();
To attach an event listener use:
eventhub.on('my-event', myCallbackFunction);
// or
eventhub.$on('my-event', myCallbackFunction);
// or
eventhub.listen('my-event', myCallbackFunction);
To detach an event listener that was attached, use:
eventhub.off('my-event', myCallbackFunction);
// or
eventhub.$off('my-event', myCallbackFunction);
// or
eventhub.remove('my-event', myCallbackFunction);
To emit, fire, an event use:
eventhub.emit('my-event', myCallbackFunction);
// or
eventhub.$emit('my-event', myCallbackFunction);
// or
eventhub.fire('my-event', myCallbackFunction);
// Initialize new object
const eventhub = new EventHub();
// For convenience set a variable to the event name
let key = 'window.loaded';
// Attach the event
eventhub.on(key, function(msg){
if (typeof msg !== 'string' || msg.length === 0) {
msg = 'Invalid message passed'
}
if (typeof alert === "function") {
// We are probably in the browser
alert(msg);
} else {
// We are probably in node
console.log(msg);
}
});
// Fire the event
eventhub.emit(
key,
'After this, the event is detached. That means goodbye!'
);
// Detach the event
eventhub.off(key);
// Try to fire again, but fail
eventhub.emit(key, 'This message will not be displayed');
After this, you are hopefully ready to start coding!
Any contributions are welcome!
git clone https://github.com/norzon/eventhub.js.git
Open with your favorite text editor and code away! Use below command to build and test code (generated code in ./dev)
npm run dev
Build the project using:
npm run build
Depending on what you coded, create or adjust the file "test/test.js". This file contains code to test this library using the "Mocha" library. Check Mocha's documentation here
Run Mocha test using:
npm run test
All set to commit. Explain the changes in the commit message and push to the repo!
eventhub.js is available under the GNU General Public License version 3