具有一个主菜单,当用户选择一个选项时,将从中执行其他JS脚本。不完全确定如何从主JS菜单执行JS。我只想退出菜单并正确运行JS。我仍然需要导出JS并以某种方式执行它吗?
runOptions();
var runOptions = function () {
inquirer.prompt({
name: "action",
type: "list",
message: "What do you want to do?",
choices: [
"Perform Magic",
"Go To Bed",
"Have a Vodka Martini"
]
}).then(function (answer) {
switch (answer.action) {
case "Perform Magic":
runMagicman();
break;
case "Go To Bed":
runSleepyTime();
break;
case "Have a Vodka Martini":
runGetDrunk();
break;
}
});
}
var runMagicman = function () {
// Exit this menu and run magicman.js
}
var runSleepyTime = function () {
// Exit this menu and run sleepytime.js
}
var runGetDrunk = function () {
// Exit this menu and run getdrunknow.js
}
答案 0 :(得分:1)
如果包含runOptions的文件是主要入口点,则无需导出runOptions函数(意味着您正在做节点./thisFile.js)。我们要导出功能或类的主要原因是按功能或用途对它们进行分组。
此外,执行这样的动态动作的一个巧妙小技巧是使用.apply(),它将为每个动作使用灵活的参数调用该函数。
runOptions();
var runOptions = function () {
inquirer.prompt({
name: "action",
type: "list",
message: "What do you want to do?",
choices: [
"Perform Magic",
"Go To Bed",
"Have a Vodka Martini"
]
}).then(function (answer) {
const functionMapping = {"Perform Magic": runMagicman, "Go To Bed": runSleepyTime, "Have a Vodka Martini": runGetDrunk };
const parameterMapping = {"Perform Magic": [answer.arg1], "Go To Bed": runSleepyTime: [answer.arg1, answer.arg2, answer.arg3], "Have a Vodka Martini": [answer.arg1, answer.arg2] };
if (functionMapping[answer.action]){
return functionMapping[answer.action].apply(null, parameterMapping[answer.action]);
}
throw "Action not found";
});
}
var runMagicman = function (arg1) {
// Exit this menu and run magicman.js
}
var runSleepyTime = function (arg1, arg2, arg3) {
// Exit this menu and run sleepytime.js
}
var runGetDrunk = function (arg1, arg2) {
// Exit this menu and run getdrunknow.js
}
希望能为您解决一切。