Error when interconnecting ipcRenderer and ipcMain in electron

北战南征 提交于 2020-01-07 04:22:14

问题


I have configured cli angular in electron, and I have a link where it execute a function that intercomunicate ipcRenderer and ipcMain:

html:

<a (click)="check()"> click </a>

component:

constructor(private _e: ElectronService) { }

check () {
   this._e.ipcRenderer.send ('conn', 'round');
   this._e.ipcRenderer.on ('conn-st', (event, args) => {
      console.log (args);
   });
}

main.js (electron):

ipcMain.on ('conn', function (event, args) {
  event.sender.send ('conn-st', 'trip');
});

The problem is that when you click once, you do it once, but when you click again it does 3, then 4, 5 and so on continuously.

And throws this error upon reaching 11:

(node:23006) Error: Possible EventEmitter memory leak detected. 11 conn-st listeners added. Use emitter.setMaxListeners() to increase limit

How do I end the connection between ipcRenderer and ipcMain?


回答1:


That error message only says, that 11 listeners to a "socket" (like the ones in UNIX) were created. Every listener creates a unique ID which is returned when creating the listener. Based on that, removing one particular listener could be done like this:

// Create a listener.
var myListener = function (event, args) {} 
ipcRenderer.on("channel", myListener);

// Delete only this one by its ID:
ipcRenderer.removeListener("channel", myListener);

But you can also delete all of the listeners that were created for a socket, like this:

// Create a few listeners.
var myListener0 = function (event, args) {};
var myListener1 = function (event, args) {};
var myListener2 = function (event, args) {};
var myListener3 = function (event, args) {};

//
ipcRenderer.on("channel", myListener0);
ipcRenderer.on("channel", myListener1);
ipcRenderer.on("channel", myListener2);
ipcRenderer.on("channel", myListener3);

// Delete all listeners for socket "channel".
ipcRenderer.removeAllListeners("channel");

This is also covered in the Electron documentation, particularly here.




回答2:


The accepted answer is nolonger correct as per the electron documentation documentation. The listener is a function and should be removed as shown below.

// Create a listener
let listener = (event, args) => {}
ipcRenderer.on("channel", listener );

//Delete the listener
ipcRenderer.removeListener("parse-cm-request", listener);


来源:https://stackoverflow.com/questions/43073820/error-when-interconnecting-ipcrenderer-and-ipcmain-in-electron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!