我到处搜索,但找不到如何创建我的 Electron 应用程序的多个实例。我正在尝试创建一个便笺应用程序,其中有一个加号窗口,该窗口应该创建一个新的便笺,而该窗口又将具有相同的加号按钮。
我已经尝试过这个,但是第一次单击便签上的加号按钮会创建一个新实例,但第二次单击加号按钮 2 会创建一个新实例,第三次单击加号按钮 4 会创建一个新实例,这是一个巨大的问题已创建
Inside main.js file
let mainWindow
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({width: 190, height: 190,frame:false,transparent:true})
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
mainWindow.on('closed', function () {
mainWindow = null
})
//when plus button is clicked it is firing a message 'create-new-instance' through ipcRenderer
ipcMain.on('create-new-instance',()=>{
console.log('create new window');
createWindow();
})
}
//this is called when for the first time the app is launched
app.on('ready', createWindow)
Inside renderer.js file where plus button is located
document.getElementById('plusButton').addEventListener("click", ()=>{
var {ipcRenderer} = require('electron')
ipcRenderer.send('create-new-instance')
})
问题是当我第一次单击加号按钮“创建新实例”时被触发,并且由于只有一个注释实例(在您第一次启动应用程序时创建),因此创建了一个新注释,使其成为 2 个注释实例两者都能够监听“create-new-instance”事件,当我第二次单击加号按钮时,两个音符都会监听此事件并创建 1 个音符,从而使其总共 4 个音符。
请帮助我或建议我任何其他替代方法:)
最佳答案
这里的主要问题是,您要在 createWindow()
内添加 create-new-instance
事件的监听器,因此每次 createWindow( )
运行时会添加另一个事件监听器,当发出 create-new-instance
时,每个监听器都会创建一个新窗口。为了避免这种情况,您需要将事件订阅移到 createWindow()
之外,这样无论调用 createWindow()
多少次,该事件都只有一个监听器。
关于javascript - 在 Electron 中创建应用程序的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40453301/