1.0.0 • Published 3 years ago
@mxttwoods/eventbus v1.0.0
@mxttwoods/eventbus
A tiny, fast, zero-dependency event bus for JavaScript.
Description
- Less than 500 bytes minified + zipped
- Zero dependencies
- Modern Syntax
- Fast
- Simple
- Typed
Installation
Just download index.js, or use npm:
yarn add @mxttwoods/eventbus
Usage
Create an EventBus instance.
const emitter = new EventBus();
Then, add handlers as you see fit.
emitter.on('my-event', (data) => {
alert('got ' + data);
});
emitter.on('my-event', (data) => {
console.log('got ' + data);
});
Remove handlers using off
.
function myHandler(data) {
console.log(data);
}
emitter.on('my-event', myHandler);
emitter.off('my-event', myHandler);
Trigger events using emit
.
// the second parameter here is the data you wish to
// pass to the event handlers
emitter.emit('my-event', {foo: 'Bar'});
If you want a handler to only run once, you can do this:
emitter.on('my-event', function foo() {
emitter.off('my-event', foo());
console.log('it worked');
});
You can register for multiple events at once like this:
function myHandler(data) {
console.log(data);
}
emitter.on('event1 event2 etc', myHandler);
emitter.off('event1 event2 etc', myHandler);
Stopping propagation isn't build into EventBus. You can work around this limitation by doing something like this:
function stopPropagation() {
const superOn = EventBus.prototype.on;
EvenBus.prototype.on = (names, fn) => {
superOn.call(this, names, (data) => {
if (!data.isCanceled) {
return fn(data);
}
return true;
});
};
}
stopPropagation();
With the above patch in place, you can do something like this in your event handlers:
emitter.on('my-event', (data) => {
data.isCanceled = true; // now, no downstream handlers should be invoked
});
Development
Install
yarn install
Build
yarn build
Test
yarn test
Author
Matthew Woods
- Website: https://matthew.codes
- Twitter: @mxttwoods
- GitHub: @mxttwoods
- LinkedIn: @matthew-t-woods
Chris Davies
- GitHub: @chrisdavies
License
Copyright © 2021 Matthew Woods.
This project is MIT licensed.
1.0.0
3 years ago