⚡ Compact event emitter for browser (and server), with all necessary features. If you need tiny and not overloaded event system, you are in the right place. 🏁 😉
- Compact -> Tiny size (~500 bytes)
- Full -> All Node's EventEmitter capabilities
- Universal -> Browser and server compatible
- Support -> IE 9+
Install, using NPM:
$ npm install act.js --save
As Node.js/Webpack/Browserify module:
// ES6 modules
import Act from 'act.js'
// CommonJS modules
const Act = require('act.js')
In browser:
<script src="https://unpkg.com/act.js/dist/act.min.js"></script>
Just call it:
const act = Act()
Or use with class/objects (composition):
const myObject = {
myFunction: function() {},
emitter: Act()
}
After you have created event emitter object, this methods become available:
Returns a copy of the events object.
act.events // { eventName: [ [Function], [Function] ] }
Add handler to event or all events, executed when this event(events) is fired. The third argument says that the handler must be prepended to the handlers array.
act.on('data', () => {})
// add handler to the beginning of the array
act.on('data', () => {}, true)
// subscribe handler for all events
act.on('*', () => {})
Add handler to event, which can be called only once. You can also use *
event type and prepend
argument in once
method.
act.once('data', () => {})
Remove handler from event, event or all events.
// Handler for 'message' event
const show = () => {}
act.on('data', show)
// remove handler
act.off('data', show)
// remove event with all handlers
act.off('data')
// remove all events
act.off()
Emit event with arguments.
act.fire('data', 34, 'Jason')
import Act from 'act.js'
const act = Act();
act.on('data', (data) => console.log('Next:', ++data.num))
act.on('notification', (name, msg) => console.log(name, ':', msg));
act.once('*', () => console.log('Called for all events.'));
console.log(act.events);
act.fire('data', { num: 11 });
act.fire('notification', 'Jason', 'Hello!');
// Otput:
// $ { data: [ [Function] ], notification: [ [Function] ], '*': [ { [Function] _once: true } ] }
// $ Next: 12
// $ Called for all events.
// $ Jason : Hello!
emitter.on(eventName, listener) -> act.on(eventName, listener)
emitter.emit(eventName, args) -> act.fire(eventName, args)
emitter.eventNames() -> Object.keys(act.events)
emitter.listenerCount(eventName) -> act.events[eventName].length
emitter.listeners(eventName) -> act.events[eventName]
emitter.once(eventName, listener) -> act.once(eventName, listener)
emitter.prependListener(eventName, listener) -> act.on(eventName, listener, true)
emitter.prependOnceListener(eventName, listener) -> act.once(eventName, listener, true)
emitter.removeAllListeners() -> act.off()
emitter.removeAllListeners(eventName) -> act.off(eventName) // Removes event listeners.
emitter.removeListener(eventName, listener) -> act.off(eventName, listener)
MIT. © 2017 Taras Batenkov