2018-12-17 02:57:34 +00:00
|
|
|
import {isFunction} from 'lodash';
|
|
|
|
import {ComponentOptions} from "vue";
|
|
|
|
import {Vue} from "vue/types/vue";
|
2018-08-19 03:13:40 +00:00
|
|
|
|
|
|
|
export default new class SocketEmitter {
|
2018-12-17 02:57:34 +00:00
|
|
|
listeners: Map<string | number, Array<{
|
|
|
|
callback: (a: ComponentOptions<Vue>) => void,
|
|
|
|
vm: ComponentOptions<Vue>,
|
|
|
|
}>>;
|
|
|
|
|
|
|
|
constructor() {
|
2018-08-19 03:13:40 +00:00
|
|
|
this.listeners = new Map();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Add an event listener for socket events.
|
|
|
|
*/
|
2018-12-17 02:57:34 +00:00
|
|
|
addListener(event: string | number, callback: (data: any) => void, vm: ComponentOptions<Vue>) {
|
2018-08-19 03:13:40 +00:00
|
|
|
if (!isFunction(callback)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!this.listeners.has(event)) {
|
|
|
|
this.listeners.set(event, []);
|
|
|
|
}
|
|
|
|
|
2018-12-17 02:57:34 +00:00
|
|
|
// @ts-ignore
|
2018-08-19 03:13:40 +00:00
|
|
|
this.listeners.get(event).push({callback, vm});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Remove an event listener for socket events based on the context passed through.
|
|
|
|
*/
|
2018-12-17 02:57:34 +00:00
|
|
|
removeListener(event: string | number, callback: (data: any) => void, vm: ComponentOptions<Vue>) {
|
2018-08-19 03:13:40 +00:00
|
|
|
if (!isFunction(callback) || !this.listeners.has(event)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-12-17 02:57:34 +00:00
|
|
|
// @ts-ignore
|
2018-08-19 03:13:40 +00:00
|
|
|
const filtered = this.listeners.get(event).filter((listener) => {
|
|
|
|
return listener.callback !== callback || listener.vm !== vm;
|
|
|
|
});
|
|
|
|
|
|
|
|
if (filtered.length > 0) {
|
|
|
|
this.listeners.set(event, filtered);
|
|
|
|
} else {
|
|
|
|
this.listeners.delete(event);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Emit a socket event.
|
|
|
|
*/
|
2018-12-17 02:57:34 +00:00
|
|
|
emit(event: string | number, ...args: any) {
|
2018-08-19 03:13:40 +00:00
|
|
|
(this.listeners.get(event) || []).forEach((listener) => {
|
2018-12-17 02:57:34 +00:00
|
|
|
listener.callback.call(listener.vm, args);
|
2018-08-19 03:13:40 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|