問(wèn)題描述
我有一個(gè)帶有 3 個(gè)窗口的 Electron
應(yīng)用程序,每個(gè)窗口都有不同的菜單.每個(gè)菜單的菜單模板代碼都很長(zhǎng),我想將其外部化.到目前為止,我沒(méi)有嘗試過(guò)任何工作.
I have an Electron
app with 3 windows and each window has a different menu. The menu template code for each menu is quite long and I would like to externalize it. So far nothing I have tried works.
我嘗試了不同的方法來(lái)模塊化"它,但出現(xiàn)了很多錯(cuò)誤.下面的方法可以設(shè)置菜單,但菜單中引用的函數(shù)都不起作用(例如 quitApplication
).
I've tried different ways to "modularize" it but got lots of errors. The approach below works to set up the menu, but none of the functions referenced in the menu work (e.g. quitApplication
).
我試圖做的事情是不可能的,還是我只是做錯(cuò)了"?
Is what I am trying to do not possible or am I just "doing it wrong"?
var test = require("./app/js/menuTest.js");
var tm = new test();
var menuTemplate = tm.getMenu();
myWindow = Menu.buildFromTemplate(menuTemplate);
<小時(shí)>
menuTest.js
function testMenu() {
this.getMenu = function () {
var menuTemplate = [
{
label: global.productData.appName,
submenu: [
{ label: 'About ' + global.productData.appName, click: () => { showAboutWindow() } },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideothers' },
{ role: 'unhide' },
{ type: 'separator' },
{ label: 'Quit', click: () => { quitApplication() }, accelerator: 'CmdOrCtrl+q' }
]
// code deleted for clarity
return menuTemplate;
}
}
module.exports = testMenu;
推薦答案
根據(jù)我對(duì)您問(wèn)題的理解,您希望將模板代碼移出主流程腳本,但將函數(shù)保留在其中.
From how I understand your question, you want to move the template code out of your main process script, but keep the functions in there.
這可以通過(guò)將菜單結(jié)構(gòu)對(duì)象移動(dòng)到一個(gè)單獨(dú)的模塊中來(lái)實(shí)現(xiàn).該模塊導(dǎo)出一個(gè)函數(shù),該函數(shù)接受一個(gè)對(duì)象,該對(duì)象引用您要在菜單中調(diào)用的函數(shù).
This can be achieved by moving the menu structure object into a separate module. The module exports a function that takes an object with references to the functions you want to call in the menu.
我相信這不會(huì)增加顯著的復(fù)雜性并且只是將菜單模板代碼外部化".
I believe this does not add significant complexity and "externalizes" just the menu template code.
menu1.js:
module.exports = function(actions) {
return [
{
label: "Foo",
submenu: [
{ label: "Bar", click: actions.bar },
{ label: "About", click: actions.about }
]
}
];
}
ma??in.js:
const {app,BrowserWindow,Menu} = require("electron");
const actions = {
bar: function () {
console.log("bar");
},
about: function () {
console.log("about");
}
};
const menu1_template = require("./menu1.js")(actions);
const menu1 = Menu.buildFromTemplate(menu1_template);
Menu.setApplicationMenu(menu1);
let mainWindow;
app.on("ready", function() {
mainWindow = new BrowserWindow();
});
這篇關(guān)于是否可以外部化電子菜單模板代碼?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!