Last active
May 7, 2017 06:02
-
-
Save blackmiaool/65d4a0dd0e06e1f3cb5d4b9d7df8c19e to your computer and use it in GitHub Desktop.
make electron ipc support callback
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
let cbUid = 0; | |
const cbMap = {}; | |
ipcRenderer.send = function(event, ...args) { | |
const last = args[args.length - 1]; | |
if (typeof last === "function") { //callback | |
cbMap[cbUid] = last; | |
args[args.length - 1] = "callback-" + cbUid; | |
cbUid++; | |
} | |
return preSend.call(ipcRenderer, event, ...args); | |
} | |
ipcRenderer.on("callback", function(event, ...args) { | |
const uid = args.pop(); | |
cbMap[uid](...args); | |
delete cbMap[uid]; | |
}); |
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 preOn = ipcMain.on; | |
ipcMain.on = function (event, cb) { | |
return preOn.call(ipcMain, event, function (event, ...args) { | |
const last = args[args.length - 1]; | |
if (last && typeof last === "string") { | |
const match = args[args.length - 1].match(/callback-(\d+)/); | |
if (match) { | |
args[args.length - 1] = function (...args) { //cb | |
mainWindow.webContents.send("callback", ...args, match[1]); | |
}; | |
} | |
} | |
return cb(event, ...args); | |
}); | |
} |
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
//renderer: | |
ipcRenderer.send("some-event", "some content", function(arg1,arg2) { | |
console.log("arg1",arg1,"arg2",arg2); | |
}); | |
//main: | |
ipcMain.on("some-event", function (event, content, cb) { | |
console.log("content",content); | |
cb("arg1","arg2"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment