Skip to content

Instantly share code, notes, and snippets.

@lifeofcoding
Forked from zaaack/electron-eventbus.js
Created May 24, 2020 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lifeofcoding/b997feb4a17c0e0d75166302045757cf to your computer and use it in GitHub Desktop.
Save lifeofcoding/b997feb4a17c0e0d75166302045757cf to your computer and use it in GitHub Desktop.
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