我正在寻找一种好方法来有时暂停一个 Action (函数/方法调用),直到用户确认他想要执行该 Action 的特定部分。我需要在不允许代码执行停止的环境中执行此操作(在我的例子中是 ActionScript,但 JavaScript 的方法应该是相同的)。
为了说明,这是引入用户提示之前的 Action 模型:
<preliminary-phase> // this contains data needed by all the following phases //
<mandatory-phase> // this will be always be executed //
<optional-phase> // this will always execute too, if in this form, but in some cases we need to ask the user if he wants to do it //
<ending-phase> // also mandatory //
我需要的是插入条件用户提示,“你想做这部分吗?”,然后做 <optional-phase>
只有当用户想要时。
<preliminary-phase>
<mandatory-phase>
if(<user-confirmation-is-needed> and not <user-response-is-positive>){
<do-nothing>
}
else{
<optional-phase>
}
<ending-phase>
当尝试在 ActionScript/JavaScript 中执行此操作时,我得到了如下信息:
<preliminary-phase>
<mandatory-phase>
if(<user-confirmation-is-needed>){
askForConfirmation(callback = function(){
if(<user-response-is-positive>)
<optional-phase>
<ending-phase>
});
return;
}
<optional-phase>
<ending-phase>
现在两个<optional-phase>
和 <ending-phase>
被重复。还因为他们使用在 <preliminary-phase>
中创建的对象如果不将所有数据传递给这些函数,我无法将它们移动到外部函数。
我目前的解决方案是将 <optional-phase>
中的每一个都附上和 <ending-phase>
在我要求确认之前声明的某些本地函数(以便它们可以访问 <preliminary-phase>
中的数据)中,我调用这些函数而不是复制代码,但代码不再按顺序排列似乎不对它被执行了。
你们会推荐什么?
注意事项:
1. askForConfirmation
是一个非阻塞函数。这意味着它的调用之后的代码会立即执行(这就是为什么我的方法中有一个 return;
)。
最佳答案
注意:我不是 100% 确定我了解您的确切情况。
命令模式可能适合这里。这与人们的建议相似。
您有一组按顺序执行的命令。
[<preliminary-phase>, <mandatory-phase>, <optional-phase>, <ending-phase>]
只需一次将命令移出数组并调用执行方法即可。
在可选阶段,检查是否需要用户确认,如果不需要则执行一个可选的代码方法,该方法调度命令完成事件,如果需要则显示警报,等待事件,检查结果并分派(dispatch)命令完成事件或调用可选方法(将运行然后分派(dispatch)命令完成)。
您还可以创建一个命令树,这样就可以清楚地说明执行流程,而不必弄乱数组。
这就是安装向导等程序的工作方式。
它的好处在于执行顺序清晰可见,您的代码被很好地分解成 block ,并且封装了每个步骤的复杂性。例如,可选阶段对结束阶段一无所知。可选阶段只知道用户可能需要在执行前得到提示,它会在内部处理所有这些。
http://en.wikipedia.org/wiki/Command_pattern
"Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing..."
关于javascript - 在进程中间提示用户确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4135452/