sg-event-emitter
v0.1.2
Published
Simple service registry
Downloads
1,056
Maintainers
Readme
Event Emitter
Very simple class allowing for dispatch custom events in DOM-like style. It's tested in production apps on both browser and node.
Usage
All available methods are:
addEventListener(name: string, listener: ()=>void)
- adds a new listener to given eventremoveEventListener(name: string, listener: ()=>void)
- removes registered listener for given event. You have to pass exactly the same function as passed previously toaddEventListener
.dispatchEvent(name: string)
- dispatches given eventsettle(host: any)
- linksaddEventListener
andremoveEventListener
from EventEmitter instance to given host object. This allows you to create really encapsulated EventEmitter instance and expose only these two public methods.
var EventEmitter = require('sg-event-emitter').EventEmitter;
//or
import {EventEmitter} from 'sg-event-emitter';
class Foo {
constructor () {
this._eventEmitter = new EventEmitter();
this._eventEmitter.settle(this); //from now this object has
//`addEventListener` and `removeEventListener` methods
}
makeSomeAction () {
this._eventEmitter.dispatchEvent('myEvent');
}
}
var foo = new Foo();
var listener = _ => console.log('dispatched');
foo.addEventListener('myEvent', listener);
foo.makeSomeAction(); //logs 'dispatched'
foo.removeEventListener('myEvent', listener);
foo.makeSomeAction(); //doesn't log anything