misc_pterodactyl-panel/resources/assets/scripts/mixins/socketio/emitter.ts

60 lines
1.6 KiB
TypeScript
Raw Normal View History

2018-12-17 02:57:34 +00:00
import {isFunction} from 'lodash';
import {ComponentOptions} from "vue";
import {Vue} from "vue/types/vue";
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() {
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>) {
if (!isFunction(callback)) {
return;
}
if (!this.listeners.has(event)) {
this.listeners.set(event, []);
}
2018-12-17 02:57:34 +00:00
// @ts-ignore
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>) {
if (!isFunction(callback) || !this.listeners.has(event)) {
return;
}
2018-12-17 02:57:34 +00:00
// @ts-ignore
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) {
(this.listeners.get(event) || []).forEach((listener) => {
2018-12-17 02:57:34 +00:00
listener.callback.call(listener.vm, args);
});
}
}