Skip to content

Commit de2e1bc

Browse files
npezza93sindresorhus
authored andcommitted
Update answerMain and answerRenderer to return a function that removes the listener (#8)
Fixes #5
1 parent a84a080 commit de2e1bc

File tree

3 files changed

+20
-6
lines changed

3 files changed

+20
-6
lines changed

readme.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,8 @@ Data to send to the receiver.
140140

141141
This method listens for a message from `ipc.callMain` defined in a renderer process and replies back.
142142

143+
Returns a function, that when called, removes the listener.
144+
143145
#### channel
144146

145147
Type: `string`
@@ -192,6 +194,8 @@ Data to send to the receiver.
192194

193195
This method listens for a message from `ipc.callRenderer` defined in the main process and replies back.
194196

197+
Returns a function, that when called, removes the listener.
198+
195199
#### channel
196200

197201
Type: `string`

source/main.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ ipc.callRenderer = (window, channel, data) => new Promise((resolve, reject) => {
3030
ipc.answerRenderer = (channel, callback) => {
3131
const {sendChannel, dataChannel, errorChannel} = util.getResponseChannels(channel);
3232

33-
ipc.on(sendChannel, async (event, data) => {
33+
const listener = async (event, data) => {
3434
const window = BrowserWindow.fromWebContents(event.sender);
3535

3636
const send = (channel, data) => {
@@ -44,7 +44,12 @@ ipc.answerRenderer = (channel, callback) => {
4444
} catch (error) {
4545
send(errorChannel, error);
4646
}
47-
});
47+
};
48+
49+
ipc.on(sendChannel, listener);
50+
return () => {
51+
ipc.removeListener(sendChannel, listener);
52+
};
4853
};
4954

5055
ipc.sendToRenderers = (channel, data) => {

source/renderer.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,18 @@ ipc.answerMain = (channel, callback) => {
2929
const window = electron.remote.getCurrentWindow();
3030
const {sendChannel, dataChannel, errorChannel} = util.getRendererResponseChannels(window.id, channel);
3131

32-
ipc.on(sendChannel, async (event, data) => {
32+
const listener = async (event, data) => {
3333
try {
3434
ipc.send(dataChannel, await callback(data));
35-
} catch (err) {
36-
ipc.send(errorChannel, err);
35+
} catch (error) {
36+
ipc.send(errorChannel, error);
3737
}
38-
});
38+
};
39+
40+
ipc.on(sendChannel, listener);
41+
return () => {
42+
ipc.removeListener(sendChannel, listener);
43+
};
3944
};
4045

4146
module.exports = ipc;

0 commit comments

Comments
 (0)