如果Web界面中涉及若干状态以及状态之间的转换,采用有限状态机管理界面可以使代码结果更清晰、更容易管理,也更容易描述。界面的状态表现为若干控件的使能、可见性或者其它视觉属性,状态之间的转换通常为事件驱动,比如点击按钮、选择下拉框等等。有限状态机的作用就是将状态和状态转换抽象出来,与具体的状态表现分离,使代码结构更加清楚。这里介绍一款有限状态机https://github.com/jakesgordon/javascript-state-machine,基于Javascript,使用起来非常简单。下面是简单的示例代码:
<!DOCTYPE html>
<html>
<head>
<title>Javascript Finite State Machine</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style>
.opened {background:yellow}
.closed {background:black}
</style>
</head>
<body>
<div >
<div id="controls">
<button id="open" onclick="Demo.open();">打开</button>
<button id="close" onclick="Demo.close();">关闭</button>
</div>
<div id="diagram" style="width: 200px; height: 200px;">
</div>
<textarea id="output">
</textarea>
</div>
<script src="dist/state-machine.js"></script>
<script src="js/demo.js"></script>
</body>
</html>
demo.js代码如下:
Demo = function() {
var output = document.getElementById('output'),
diagram = document.getElementById('diagram'),
open = document.getElementById('open'),
close = document.getElementById('close')
count = 0;
var log = function(msg, separate) {
count = count + (separate ? 1 : 0);
output.value = count + ": " + msg + "\n" + (separate ? "\n" : "") + output.value;
refreshUI();
};
var refreshUI = function() {
setTimeout(function() {
diagram.className = fsm.state;
open.disabled = fsm.cannot('open', true);
close.disabled = fsm.cannot('close', true);
}, 0); // defer until end of current tick to allow fsm to complete transaction
};
var fsm = new StateMachine({
transitions: [
{ name: 'start', from: 'none', to: 'closed' },
{ name: 'open', from: 'closed', to: 'opened' },
{ name: 'close', from: 'opened', to: 'closed' }
],
methods: {
onBeforeTransition: function(lifecycle) {
log("BEFORE: " + lifecycle.transition, true);
},
onLeaveState: function(lifecycle) {
log("LEAVE: " + lifecycle.from);
},
onEnterState: function(lifecycle) {
log("ENTER: " + lifecycle.to);
},
onAfterTransition: function(lifecycle) {
log("AFTER: " + lifecycle.transition);
},
onTransition: function(lifecycle) {
log("DURING: " + lifecycle.transition + " (from " + lifecycle.from + " to " + lifecycle.to + ")");
},
}
});
fsm.start();
return fsm;
}();
网友评论