您可以将应用程序建模为状态机,以对复杂的工作流程进行建模。
定义状态机:
- 定义您的应用程序可以处于的所有状态。
- 定义在每个状态中允许的操作集。每个操作都会将应用程序的状态从一种状态转换到另一种状态。
- 为每个操作编写业务逻辑,其中包括对服务器的持久更改以及相应地更改视图的状态。
这种设计类似于创建DFA,但您可以根据需要添加额外的行为。
如果这听起来太抽象,这里有一个简单状态机的例子。
假设您正在构建一个简单的登录应用程序。
设计状态和动作
INITIAL_STATE:用户第一次访问页面,两个字段都是空的。假设您只想使 username 可见,而不是 password 在此状态下。 (类似于新的 Gmail 工作流程)
USERNAME_ENTRY_STATE:当用户输入用户名并点击return时,在此状态下,您希望显示用户名并隐藏密码。您可以将onUsernameEntered 作为此状态下的操作。
PASSWORD_ENTRY_STATE:现在,用户名视图将被隐藏,而密码视图将被显示。当用户点击return 时,您必须检查用户名和密码是否匹配。让我们将此操作称为onPasswordEntered
AUTHENTICATED_STATE:当服务器验证用户名/密码组合时,假设您要显示主页。让我们将此操作称为onAuthenticated
我暂时省略了处理身份验证失败的情况。
设计视图:
在这种情况下,我们有 UsernameView 和 PasswordView
设计模型:
单个Auth 模型足以满足我们的示例。
设计路线:
查看使用 Marionette 处理路线的最佳做法。状态机应该在登录路由中初始化。
示例伪代码:
我只展示了与管理状态机相关的代码。渲染和事件处理可以照常处理;
var UsernameView = Backbone.View.extend({
initialize: function(options) {
this.stateMachine = options.stateMachine;
},
onUserNameEntered: function() {
username = //get username from DOM;
this.stateMachine.handleAction('onUserNameEntered', username)
},
show: function() {
//write logic to show the view
},
hide: function() {
//write logic to hide the view
}
});
var PasswordView = Backbone.View.extend({
initialize: function(options) {
this.stateMachine = options.stateMachine;
},
onPasswordEntered: function() {
password = //get password from DOM;
this.stateMachine.handleAction('onPasswordEntered', password)
},
show: function() {
//write logic to show the view
},
hide: function() {
//write logic to hide the view
}
});
每个状态都有一个 entry 函数来初始化视图和 exit 函数来清理视图。每个状态还将具有与该状态下的有效操作相对应的功能。例如:
var BaseState = function(options) {
this.stateMachine = options.stateMachine;
this.authModel = options.authModel;
};
var InitialState = BaseState.extend({
entry: function() {
//show the username view
// hide the password view
},
exit: function() {
//hide the username view
},
onUsernameEntered: function(attrs) {
this.authModel.set('username', attrs.username');
this.stateMachine.setState('PASSWORD_ENTRY_STATE');
}
});
同样,您可以为其他状态编写代码。
最后是状态机:
var StateMachine = function() {
this.authModel = new AuthModel;
this.usernameView = new UserNameView({stateMachine: this});
//and all the views
this.initialState = new InitialState({authModel: this.authModel, usernameView: this.usernameView});
//and similarly, all the states
this.currentState = this.initialState;
};
StateMachine.prototype = {
setState: function(stateCode) {
this.currentState.exit(); //exit from currentState;
this.currentState = this.getStateFromStateCode(stateCode);
this.currentState.entry();
},
handleAction: function(action, attrs) {
//check if action is valid for current state
if(actionValid) {
//call appropriate event handler in currentState
}
}
};
StateMachine.prototype.constructor = StateMachine;
对于一个简单的应用程序,这似乎是一种矫枉过正。对于复杂的业务逻辑,这是值得的。这种设计模式会自动防止双击按钮等情况,因为您已经进入下一个状态,而新状态无法识别前一个状态的动作。
一旦您构建了状态机,您团队的其他成员就可以插入他们的状态和视图,也可以在一个地方看到全局。
诸如 Redux 之类的库可以完成此处所示的一些繁重工作。所以你可能也想考虑 React + Redux + Immutable.js。