Act
- Compact -> Tiny size (~500 bytes)
- Full -> All Node's EventEmitter capabilities
- Universal -> Browser and server compatible
- Support -> IE 9+
How to Install
Install, using NPM:
$ npm install act.js --save
Include
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>
How to Use
Just call it:
const act = Act()
Or use with class/objects (composition):
const myObject = {
myFunction: function() {},
emitter: Act()
}
API methods
After you have created event emitter object, this methods become available:
Properties
events
Returns a copy of the events object.
act.events // { eventName: [ [Function], [Function] ] }
Methods
on(event, handler, prepend)
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('*', () => {})
fire(event[,arguments])
Emit event with arguments.
act.fire('data', 34, 'Jason')
once(event, handler, prepend)
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', () => {})
off(event[,handler])
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()
Example
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!
License
MIT. © 2017 Taras Batenkov