alex8088 / electron-toolkit

Toolkit for Electron
MIT License
121 stars 6 forks source link

ipcRenderer.removeListener不生效 #10

Closed zhangmingming3 closed 7 months ago

zhangmingming3 commented 7 months ago

Describe the bug

主进程: setInterval(() => { mainWindow.webContents.send("sendMessage", {id: 1, type: 4}) }, 5000); 渲染进程,vue组件 onMounted(()=>{ window.electron.ipcRenderer.on('sendMessage',getMessage) }) onBeforeUnmount(()=>{ window.electron.ipcRenderer.removeListener('sendMessage',getMessage) }) const getMessage=(val,message)=>{ console.log(val); console.log(message); } 组件销毁后,依旧能接收消息并在控制台打印,频繁创建销毁该组件,打印次数会累加

Electron-Toolkit Version

3.0.0

Electron Version

28.2.0

Validations

alex8088 commented 7 months ago

@zhangmingming3 https://github.com/alex8088/electron-toolkit/tree/master/packages/preload#get-started

zhangmingming3 commented 7 months ago

还是不理解为什么electron.ipcRenderer.removeListener('sendMessage',getMessage)不生效;但removeAllListeners是生效的。

alex8088 commented 7 months ago

因为 preload 在数据传递时会进行序列化和反序列化,绑定的函数即getMessage并不是同一个对象,所以这种移除方式是不成功的,使用返回的removeListener函数去preload中移除监听,即移除真正的绑定的函数getMessage

https://www.electronjs.org/zh/docs/latest/api/context-bridge#api-functions

alex8088 commented 7 months ago

removeAllListeners,则无需理会绑定的函数,则能够成功

alex8088 commented 7 months ago

简单理解就是preload和renderer的进程内存不共享