salix/front/core/lib/event-emitter.js

87 lines
2.4 KiB
JavaScript
Raw Normal View History

2018-10-22 09:04:17 +00:00
/**
* Implemented by all those classes that emit events.
*/
2018-10-18 07:24:20 +00:00
export default class EventEmitter {
/**
* Connects to an object event.
*
* @param {String} eventName The event name
* @param {Function} callback The callback function
* @param {Object} thisArg The scope for the callback or %null
*/
on(eventName, callback, thisArg) {
if (!this.$events)
this.$events = {};
if (!this.$events[eventName])
this.$events[eventName] = [];
this.$events[eventName].push({callback, thisArg});
}
/**
* Disconnects all handlers for callback.
*
* @param {Function} callback The callback function
*/
off(callback) {
if (!this.$events) return;
2019-10-16 06:56:13 +00:00
for (let event in this.$events) {
for (let i = 0; i < event.length; i++) {
2018-10-18 07:24:20 +00:00
if (event[i].callback === callback)
event.splice(i--, 1);
2019-10-16 06:56:13 +00:00
}
}
2018-10-18 07:24:20 +00:00
}
/**
* Disconnects all instance callbacks.
*
* @param {Object} thisArg The callbacks instance
*/
disconnect(thisArg) {
if (!this.$events) return;
2019-10-16 06:56:13 +00:00
for (let event in this.$events) {
for (let i = 0; i < event.length; i++) {
2018-10-18 07:24:20 +00:00
if (event[i].thisArg === thisArg)
event.splice(i--, 1);
2019-10-16 06:56:13 +00:00
}
}
2018-10-18 07:24:20 +00:00
}
/**
* Emits an event.
*
* @param {String} eventName The event name
* @param {Object} args Arguments to pass to the callbacks
2018-10-18 07:24:20 +00:00
*/
emit(eventName, args) {
2018-10-18 07:24:20 +00:00
if (!this.$events || !this.$events[eventName])
return;
args = Object.assign({$this: this}, args);
2018-10-18 07:24:20 +00:00
let callbacks = this.$events[eventName];
for (let callback of callbacks)
callback.callback.call(callback.thisArg, args);
2018-10-18 07:24:20 +00:00
}
/**
* Links the object with another object events.
*
* @param {Object} propValue The property and the new value
* @param {Object} handlers The event handlers
*/
linkEvents(propValue, handlers) {
for (let prop in propValue) {
let value = propValue[prop];
if (this[prop])
this[prop].disconnect(this);
this[prop] = value;
2019-10-16 06:56:13 +00:00
if (value) {
2018-10-18 07:24:20 +00:00
for (let event in handlers)
value.on(event, handlers[event], this);
2019-10-16 06:56:13 +00:00
}
2018-10-18 07:24:20 +00:00
}
}
}
EventEmitter.$inject = ['$element', '$scope'];