import { CallbackStore } from './CallbackStore' import { EventBusInterface } from './EventBusInterface' import { Event } from '../Events' import { IpcRenderer } from 'electron' export class IpcRendererEventBus implements EventBusInterface { private ipc: IpcRenderer private callbacks: Array = [] constructor(ipc: IpcRenderer) { this.ipc = ipc } public subscribe(event: Event, callback: (msg: MessageType) => void) { const wrappedCallback = (_: any, arg: any) => { callback(arg) } console.log('subscribing', event.topic) this.ipc.on(event.topic, wrappedCallback) this.callbacks.push({ callback, wrappedCallback, }) } public unsubscribeAll(event: Event) { this.ipc.removeAllListeners(event.topic) } public unsubscribe(event: Event, callback: any) { const item = this.callbacks.find(store => store.callback === callback) if (!item) { return } this.ipc.removeListener(event.topic, item.wrappedCallback) this.callbacks = this.callbacks.filter(a => a !== item) } public emit(event: Event, msg: MessageType) { this.ipc.send(event.topic, msg) } }