| 2 | import {IpcRenderer, IpcRendererEvent} from 'electron'; |
| 3 | import electron from 'electron'; |
| 4 | export default class Client { |
| 5 | emitter: EventEmitter; |
| 6 | ipc: IpcRenderer; |
| 7 | id!: string; |
| 8 | constructor() { |
| 9 | this.emitter = new EventEmitter(); |
| 10 | this.ipc = electron.ipcRenderer; |
| 11 | if (window.__rpcId) { |
| 12 | setTimeout(() => { |
| 13 | this.id = window.__rpcId; |
| 14 | this.ipc.on(this.id, this.ipcListener); |
| 15 | this.emitter.emit('ready'); |
| 16 | }, 0); |
| 17 | } else { |
| 18 | this.ipc.on('init', (ev: IpcRendererEvent, uid: string) => { |
| 19 | // we cache so that if the object |
| 20 | // gets re-instantiated we don't |
| 21 | // wait for a `init` event |
| 22 | window.__rpcId = uid; |
| 23 | this.id = uid; |
| 24 | this.ipc.on(uid, this.ipcListener); |
| 25 | this.emitter.emit('ready'); |
| 26 | }); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | ipcListener = (event: any, {ch, data}: {ch: string; data: any}) => { |
| 31 | this.emitter.emit(ch, data); |
| 32 | }; |
| 33 | |
| 34 | on(ev: string, fn: (...args: any[]) => void) { |
| 35 | this.emitter.on(ev, fn); |
| 36 | } |
| 37 | |
| 38 | once(ev: string, fn: (...args: any[]) => void) { |
| 39 | this.emitter.once(ev, fn); |
| 40 | } |
| 41 | |
| 42 | emit(ev: string, data: any) { |
| 43 | if (!this.id) { |
| 44 | throw new Error('Not ready'); |
| 45 | } |
| 46 | this.ipc.send(this.id, {ev, data}); |
| 47 | } |
| 48 | |
| 49 | removeListener(ev: string, fn: (...args: any[]) => void) { |
| 50 | this.emitter.removeListener(ev, fn); |
| 51 | } |
| 52 | |
| 53 | removeAllListeners() { |
| 54 | this.emitter.removeAllListeners(); |
| 55 | } |
| 56 | |
| 57 | destroy() { |
| 58 | this.removeAllListeners(); |
| 59 | this.ipc.removeAllListeners(this.id); |
| 60 | } |
| 61 | } |