Package Exports
- event-emitter-object
- event-emitter-object/source
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (event-emitter-object) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Javascript Event Emitter Object
A simple event emitter object that you can plug into your javascript libraries.
API is very similar to the node.js events.
Install
npm install event-emitter-objectImport
The default file imported by the module is polyfilled, bundled dist/index.js file:
const EventEmitter = require('event-emitter-object')If you already have a compiler like babel or already polyfilling your codebase, using ./source/index.js recommended.
const EventEmitter = require('event-emitter-object/source')Use
Let's say you have a state manager object to control the state of your app.
function StateManager() {}
StateManager.prototype.updateState = function updateState(payload) {
// update state
// ...
// and inform listeners that the state has just updated
this.emit('update')
}
module.exports = StateManagerTo plug event emitter into your state manager:
StateManager.prototype = Object.assign({}, StateManager.prototype, EventEmitter.prototype)Now, you can listen and emit events within your state manager:
const state = new StateManager()
state.on('update', function() {
console.log('State updated!')
})API
on(eventName, callback, opts)
Registers a new listener for a certain event.
emitter.on('someEvent', function() {
console.log('Some event happened in some emitter.')
}, {
once: true // default is false
})once(eventName, callback)
This is a shortcut for the on method with {once: true}:
// instead of doin this:
emitter.on('someEvent', function(){}, {once: true})
// you can do this:
emitter.once('someEvent', function(){})emit(eventName, args)
Emits a certain event with arguments.
emitter.emit('someEvent')
// or with arguments
emitter.on('anotherEvent', function(arg1, arg2) {
console.log('Another event emitted with arguments: ', arg1, arg2)
})
emitter.emit('anotherEvent', ['hello', 'world'])removeListeners(eventName)
Removes all listeners that belong to a certain event.
emitter.removeListeners('someEvent')flush()
Removes all events and listeners.
emitter.flush()