emit.js
Efficient minimalist event emitter in JavaScript.
Installation
It is available with bower or npm:
bower install emit.js
npm install emit.js
Include emit.min.js
to the HTML, and the emit
object is now available in the global scope:
<script type="text/javascript" src="/path/to/bower_components/emit.js/dist/emit.min.js"></script>
Alternately, you can use a module manager to avoid global scoping:
var emit = require('emit.js');
import emit from 'emit.js';
Usage
Create an event emitter
var emitter = emit();
Register listener on it
You can register a listener with on
and once
method. Listeners registered with once
will be triggered only once.
emitter.on('event', function(...args) {
console.log('I am a listener');
});
emitter.on(/^event(foo)?$/, function(...args) {
console.log('I am a listener');
});
emitter.on(function(event) {
return event.substr(0, 5) === 'hello';
}, function(...args) {
console.log('I am a listener');
});
emitter.once('event', function(...args) {
console.log('I am triggered only once');
});
Unregister a listener
When you register a listener, you get in return a callback to unregister it:
var unregister = emitter.on('event', function(...args) {
if (...) {
unregister();
}
console.log('I am a listener');
});
Emit an event
To emit an event, just use the emit
method:
emitter.emit('event', arg1, arg2, ...);
emitter.emit('event').then(function() {
}, function(error) {
});
Removing all listeners
You can remove all listeners by calling the removeAllListeners
method.
Development
Installation
make install
Build
make build
or make build-dev
(unminified version)
Watch
make watch
Test
make test
Contributing
All contributions are welcome and must pass the tests. If you add a new feature, please write tests for it.
License
This application is available under the MIT License.