2015-12-29 07:05:36 +01:00
|
|
|
/**
|
|
|
|
* Event emitter class
|
|
|
|
*/
|
2015-12-27 12:08:14 +01:00
|
|
|
export class Emitter {
|
|
|
|
constructor() {
|
2015-12-29 07:05:36 +01:00
|
|
|
/**
|
|
|
|
* Events object
|
|
|
|
* @type {Object}
|
|
|
|
*/
|
2015-12-27 12:08:14 +01:00
|
|
|
this.events = {};
|
|
|
|
}
|
|
|
|
|
2015-12-29 07:05:36 +01:00
|
|
|
/**
|
|
|
|
* Subscribe to an event
|
2016-01-03 03:49:04 +01:00
|
|
|
* @param {Array} evts Collection of event names
|
2015-12-29 07:05:36 +01:00
|
|
|
* @param {Function} fn Function invoked when event is emitted
|
|
|
|
*/
|
2016-01-03 03:49:04 +01:00
|
|
|
on(evts, fn) {
|
|
|
|
evts.forEach((evt)=> {
|
|
|
|
this.events[evt] = this.events[evt] || [];
|
|
|
|
this.events[evt].push(fn);
|
|
|
|
});
|
2015-12-27 12:08:14 +01:00
|
|
|
}
|
|
|
|
|
2015-12-29 07:05:36 +01:00
|
|
|
/**
|
|
|
|
* Unsubscribe to an event
|
2016-01-03 03:49:04 +01:00
|
|
|
* @param {Array} evts Collection of event names
|
2015-12-29 07:05:36 +01:00
|
|
|
* @param {Function} fn Function invoked when event is emitted
|
|
|
|
*/
|
2016-01-03 03:49:04 +01:00
|
|
|
off(evts, fn) {
|
|
|
|
evts.forEach((evt)=> {
|
|
|
|
if(evt in this.events) {
|
|
|
|
this.events[evt].splice(this.events[evt].indexOf(fn), 1);
|
|
|
|
}
|
|
|
|
});
|
2015-12-27 12:08:14 +01:00
|
|
|
}
|
|
|
|
|
2015-12-29 07:05:36 +01:00
|
|
|
/**
|
|
|
|
* Emit an event
|
|
|
|
* @param {String} evt Event name followed by any other argument passed to
|
|
|
|
* the invoked function
|
|
|
|
*/
|
2015-12-27 12:08:14 +01:00
|
|
|
emit(evt /*, args...*/) {
|
2016-01-03 03:49:04 +01:00
|
|
|
if(evt in this.events) {
|
|
|
|
for(let i = 0; i < this.events[evt].length; i++) {
|
|
|
|
this.events[evt][i].apply(this, [].slice.call(arguments, 1));
|
|
|
|
}
|
2015-12-27 12:08:14 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|