cocktail-trait-eventable
CocktailJS Trait Extension
AA trait to use an Emitter as a delegate.
Install
npm install cocktail --savenpm install cocktail-trait-eventable --save
Trait requires (glue code)
A getEmitter
method is required as a glue code for this trait.
getEmitter()
: should return an EventEmitter instance or any other object with the same api as node events.EventEmitter
class.
Usage
MyClass.js
var cocktail = Eventable = EventEmitter = EventEmitter; cocktail;
And then in your index you can do:
index.js
var MyClass = obj; obj = ; //we can call `on` or `addListener` here since our MyClass is Eventableobj; obj;
API
The following methods will be publicly available on the host class:
addListener(eventName, handler)
: Adds a listener to the end of the listeners array for the specified event.- eventName: {String} the event name to be listened to.
- handler: {Function} the event handler.
myObj;
addListener(options)
: Adds a listener to the end of the listeners array for the specified event.- options: {Object} an object containing value-pairs of event name and handler and an optional scope.
myObj;
emit(eventName, arg1, arg2, ..., argN)
: Execute each of the listeners in order with the supplied arguments.- eventName: {String} the event name to be listened to.
- arg1..N: {Any} arguments to be passed as parameters in the event handler.
myObj;
on(eventName, handler)
: IdemaddListener
method.
myObj;
on(options)
: IdemaddListener
method.
myObj;
once(eventName, handler)
: Adds a one time event listener.- eventName: {String} the event name to be listened to.
- handler: {Function} the event handler.
myObj;
once(options)
: Adds a one time event listener.- options: {Object} an object containing value-pairs of event name and handler and an optional scope.
myObj;
removeListener(eventName, handler)
: Removes the given handler for the event.- eventName: {String} the event name.
- handler: {Function} the event handler.
myObj;
removeListener(options)
: Removes the given handler for the event.- options: {Object} an object containing value-pairs of event name and handler.
myObj;
removeAllListeners(eventName)
: Remove all listeners for the given event.- eventName: {String} the event name.
myObj;