hyper/app/rpc.js

55 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

const {EventEmitter} = require('events');
const {ipcMain} = require('electron');
2016-07-25 10:01:01 -08:00
const uuid = require('uuid');
2016-06-30 22:01:04 -08:00
class Server extends EventEmitter {
constructor(win) {
super();
2016-06-30 22:01:04 -08:00
this.win = win;
this.ipcListener = this.ipcListener.bind(this);
2016-07-25 10:01:01 -08:00
if (this.destroyed) {
return;
}
2016-07-25 10:01:01 -08:00
const uid = uuid.v4();
this.id = uid;
ipcMain.on(uid, this.ipcListener);
// we intentionally subscribe to `on` instead of `once`
// to support reloading the window and re-initializing
// the channel
this.wc.on('did-finish-load', () => {
this.wc.send('init', uid);
2016-06-30 22:01:04 -08:00
});
}
get wc() {
2016-06-30 22:01:04 -08:00
return this.win.webContents;
}
ipcListener(event, {ev, data}) {
super.emit(ev, data);
2016-06-30 22:01:04 -08:00
}
emit(ch, data) {
this.wc.send(this.id, {ch, data});
2016-06-30 22:01:04 -08:00
}
destroy() {
2016-06-30 22:01:04 -08:00
this.removeAllListeners();
this.wc.removeAllListeners();
if (this.id) {
ipcMain.removeListener(this.id, this.ipcListener);
} else {
// mark for `genUid` in constructor
this.destroyed = true;
}
}
}
module.exports = win => {
2016-06-30 22:01:04 -08:00
return new Server(win);
};