如何为IPCmain.on添加事件监听器?

问题描述 投票:0回答:1

我正在尝试为我的应用程序制作一个按钮,当您按下它时,会弹出一个“记事卡”。但现在,当我尝试将“事件”传递到 IPCmain.on 的参数之一时,它说它已被弃用。我该怎么办?

main.js

const {app, BrowserWindow, ipcMain} = require('electron'); 

let mainWindow

function createWindow() {
  mainWindow = new BrowserWindow({width: 800, height: 600})

  mainWindow.loadFile('index.html')
}

app.whenReady().then(createWindow); 

app.on('window-all-closed', ()=> {
  app.quit();
})

app.on('activate', () => {
  if(BrowserWindow.getAllWindows().length === 0){
    createWindow(); 
  }
}); 

ipcMain.on('createNote', () => {
  const noteText = 'New Note'; 
  mainWindow.webContents.send('noteCreated', noteText);
});

创建.js

const { ipcRenderer } = require('electron'); 

document.getElementById('createButton').addEventListener('click', ()=>{
  ipcRenderer.send('createNote'); 
}); 

ipcRenderer.on('noteCreated', (noteText) => {
  const noteContainer = document.getElementById('noteContainer'); 
  const noteCard = document.createElement('div'); 
  noteCard.textContent = noteText; 
  noteContainer.appendChild(noteCard); 
});  

index.html

<!DOCTYPE html>
<html lang="en">
  <head> 
    <meta charset = "UTF-8"> 
    <meta name = "viewport" content="width=device-width, initial-scale=1.0">
    <script src="create.js"> </script>
    <title> ToDo </title>
  </head>

  <body>
    <div id="Header">
      <h1> Header </h1>
      <button id="createButton"> Create </button>
    </div>
    <div id="noteContainer"></div>
  </body>
</html>

我尝试将 create.js 中的变量“createNote”传递到参数中,但这不起作用。

javascript electron event-handling
1个回答
0
投票

出现错误时,最好检查所有相关的文档。在那里,我们可以看到渲染器进程中

noteCreated
事件的侦听器应该具有非常不同的签名。

事实上,文档列出了 Electron 将传递给监听器函数的两个参数,即

event
(其类型为
IpcRendererEvent
)和
...args
(其类型为
any[]
)。这些点告诉您,您可以在
args
处期待多个参数,请参阅 MDN

args
将是您传递给
webContents.send()
的任何内容。因此,您应该将侦听器函数修改为

ipcRenderer.on('noteCreated', (event, noteText) => {
  const noteContainer = document.getElementById('noteContainer'); 
  const noteCard = document.createElement('div'); 
  noteCard.textContent = noteText; 
  noteContainer.appendChild(noteCard); 
});  

参数的命名无关紧要,只有它们的顺序和位置很重要:第一个参数始终是

IpcRendererEvent
(它允许您直接与消息的发送者通信),后跟您提供的任何参数。

© www.soinside.com 2019 - 2024. All rights reserved.