gpt4 book ai didi

javascript - 单击取消时,为什么 Electron showMessageBox Sync复制自己?

转载 作者:行者123 更新时间:2023-12-03 12:36:49 26 4
gpt4 key购买 nike

因此,问题是:单击按钮后,我将打开一个类型为“info”的 Electron messageBox。它具有“确定”和“取消”选项。如果单击“确定”,没问题。但是,当我单击“取消”,然后再次单击我的按钮时,每次单击按钮并每次选择“取消”时,都会连续打开另一个messageBox。可以这么说,单击“确定”将结束循环,因为该名称将被添加到列表中,之后将被忽略。尽管如果在复制框时多次单击“确定”,则名称将被多次添加,就像它不适用于最新版本的名称列表一样(可能是这种情况)。
我一直在使用contextBridge,所以调用从我的主脚本转到preload.js,再到main.js,再返回。我认为问题不在我的事件监听器中,因为每次单击按钮时我只会看到一次对checkName的调用。这是我的代码逻辑吗?我对 Electron 学有点陌生,所以我现在不确定这是什么原因造成的,并且还无法从文档/其他线程中收集到任何有关此行为的信息。

//index.js
window.onload = function(){
document.getElementById('myButton').addEventListener('click', checkName);
}

function checkName(){
var name = document.getElementById('myInput').value;
window.api.send("sendNames", "");
window.api.receive("getNames", (names) => {
//I split names into an array by '\r\n' here
if(!names.includes(name)){
window.api.confirm("confirmName", "This is the first time this name has been used, would you like
to add it now?");
window.api.receive("getConfirmation", (result) => {
//I format names as a string here before sending back
if(result == 0) window.api.update("updateNames", names);
}
}
}
}
//preload.js
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
let validChannels = ["sendNames"];
if (validChannels.includes(channel)){
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["getNames", "getConfirmation"];
if (validChannels.includes(channel)){
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
},
update: (channel, data) => {
let validChannels = ["updateNames"];
if(validChannels.includes(channel)){
ipcRenderer.send(channel, data);
}
},
confirm: (channel, data) => {
let validChannels = ["confirmName"];
if(validChannels.includes(channel)){
ipcRenderer.send(channel, data);
}
}
}
);
//main.js
ipcMain.on("sendNames", (event, args) => {
const fs = require('fs');
var allUsers = fs.readFileSync('./nameList.txt', 'utf-8');
mainWindow.webContents.send("getNames", allUsers);
});

ipcMain.on("updateNames", (event, args) => {
const fs = require('fs');
fs.writeFileSync('./nameList.txt', args);
});

ipcMain.on("confirmName", (event, args) => {
var options = {
type: 'info',
buttons: ['OK', 'Cancel'],
noLink: true,
cancelId: 1,
title: 'Confirm',
message: args
};
mainWindow.webContents.send("getConfirmation", dialog.showMessageBoxSync(mainWindow, options));
});

最佳答案

在创建另一个监听器之前删除所有监听器似乎可以解决此问题。我本来希望针对要复制的特定 channel ,但是这似乎并没有改变任何行为。我没有看到对其他监听器功能有任何不利影响,因此我将其视为解决我的问题的方法。

confirm: (channel, data) => {
ipcRenderer.removeAllListeners();
let validChannels = ["confirmName"];
if(validChannels.includes(channel)){
ipcRenderer.send(channel, data);
}
}

关于javascript - 单击取消时,为什么 Electron showMessageBox Sync复制自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66709827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com