@mxttwoods/eev
A tiny, fast, zero-dependency event emitter for JavaScript.
Description
- Less than 500 bytes minified + zipped
- Fast
- Zero dependencies
- Simple
Installation
Just download index.js, or use npm:
yarn add @mxttwoods/eev
Usage
Create an Eev instance.
const eventBus = new Eev();
Then, add handlers as you see fit.
eventBus.on('my-event', (data) => {
alert('got ' + data);
});
eventBus.on('my-event', (data) => {
console.log('got ' + data);
});
Remove handlers using off
.
function myHandler(data) {
console.log(data);
}
eventBus.on('my-event', myHandler);
eventBus.off('my-event', myHandler);
Trigger events using emit
.
// The second parameter here is the data you wish to
// pass to the event handlers
eventBus.emit('my-event', { foo: 'Bar' });
If you want a handler to only run once, you can do this:
eventBus.on('my-event', function foo() {
eventBus.off('my-event', foo());
console.log('it worked');
});
You can register for multiple events at once like this:
function myHandler(data) {
console.log(data);
}
eventBus.on('event1 event2 etc', myHandler);
eventBus.off('event1 event2 etc', myHandler);
Stopping propagation isn't build into Eev. You can work around this limitation by doing something like this:
function stopPropagation() {
const superOn = Eev.prototype.on;
Eev.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:
eventBus.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.