-
-
Save lifeofcoding/b997feb4a17c0e0d75166302045757cf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const EventEmitter = require('events') | |
const electron = require('electron') | |
export default class EventBus extends EventEmitter { | |
constructor(name='default') { | |
super() | |
this._name = name | |
this._baseEventKey = `EventBus-${name}:` | |
} | |
on(event, listender) { | |
const ipc = electron.ipcMain || electron.ipcRenderer | |
ipc.on(this._baseEventKey + event, (e, argsJson) => { | |
const args = JSON.parse(argsJson) | |
return listender && listender(...args) | |
}) | |
return super.on(event, listender) | |
} | |
emit(event, ...args) { | |
const webContents = electron.webContents | |
const remote = electron.remote | |
const ipcRenderer = electron.ipcRenderer | |
const allContents = webContents.getAllWebContents() | |
const ipcArgs = [this._baseEventKey + event, JSON.stringify(Array.from(args))] | |
if (electron.ipcRenderer) { // renderer process | |
const curContents = remote.getCurrentWebContents() | |
allContents | |
.filter(contents => contents.id !== curContents.id) | |
.forEach(contents => contents.send(...ipcArgs)) | |
ipcRenderer.send() | |
} else { // main process | |
allContents | |
.forEach(contents => contents.send(...ipcArgs)) | |
} | |
return super.emit(event, ...args) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment