javascript-state-machine
<h3 id="使用场景">使用场景</h3><ol>
<li>
<p>一个由一个或多个动态变化的属性导致发生不同行为的对象,在与外部事件产生互动时,其内部状态就会改变,从而使得系统的行为也随之发生变化,那么这个对象,就是有状态的对象</p>
</li>
<li>
<p>代码中包含大量与对象状态有关的条件语句,像是if else或switch case语句,且这些条件执行与否依赖于该对象的状态。</p>
</li>
</ol>
<h3 id="installation">Installation</h3>
<pre><code class="language-bash">npm install --save-dev javascript-state-machine
</code></pre>
<h3 id="usage">Usage</h3>
<pre><code class="language-js">var StateMachine = require('javascript-state-machine')
var fsm = new StateMachine({
init: 'solid',
transitions: [
{ name: 'melt', from: 'solid', to: 'liquid' },
{ name: 'freeze', from: 'liquid', to: 'solid' },
{ name: 'vaporize', from: 'liquid', to: 'gas' },
{ name: 'condense', from: 'gas', to: 'liquid' },
],
methods: {
onMelt: function() {
console.log('I melted')
},
onFreeze: function() {
console.log('I froze')
},
onVaporize: function() {
console.log('I vaporized')
},
onCondense: function() {
console.log('I condensed')
},
},
})
console.log(fsm.allStates())
console.log(fsm.state)
fsm.state //获取当前状态机对象fsm的状态
//改变状态机状态的几个过渡方法
fsm.melt()
fsm.freeze()
fsm.vaporize()
fsm.condense()
//状态机提供一系列工具方法
fsm.is(s) // return true 如果当前状态机状态为 s
fsm.can(t) // return true 如果过渡方法t可以从当前状态触发
fsm.cannot(t) // return true 如果当前状态下不能发生过渡方法t
fsm.transitions() // 返回从当前状态可以过渡到的状态的列表
fsm.allTransitions() // 返回所有过渡方法的列表
fsm.allStates() // 返回状态机有的所有状态的列表
</code></pre>
<ul>
<li>
<p>form:当前行为从哪个状态来</p>
</li>
<li>
<p>to:当前行为执行完会过渡到哪个状态</p>
</li>
<li>
<p>name:当前行为的名字</p>
</li>
</ul>
<p>Observing Lifecycle Events</p>
<pre><code class="language-js">fsm.observe({
onStep: function() { console.log('stepped'); }
onA: function() { console.log('entered state A'); }
onB: function() { console.log('entered state B'); }
});
</code></pre>
<p>Lifecycle Event Names</p>
<pre><code class="language-js">var fsm = new StateMachine({
transitions: [
{ name: 'do-with-dash', from: 'has-dash', to: 'has_underscore' },
{ name: 'do_with_underscore', from: 'has_underscore',to: 'alreadyCamelized' },
{ name: 'doAlreadyCamelized', from: 'alreadyCamelize', to: 'has-dash' }
],
methods: {
onBeforeDoWithDash: function() { /* ... */ },
onBeforeDoWithUnderscore: function() { /* ... */ },
onBeforeDoAlreadyCamelized: function() { /* ... */ },
onLeaveHasDash: function() { /* ... */ },
onLeaveHasUnderscore: function() { /* ... */ },
onLeaveAlreadyCamelized: function() { /* ... */ },
onEnterHasDash: function() { /* ... */ },
onEnterHasUnderscore: function() { /* ... */ },
onEnterAlreadyCamelized: function() { /* ... */ },
onAfterDoWithDash: function() { /* ... */ },
onAfterDoWithUnderscore: function() { /* ... */ },
onAfterDoAlreadyCamelized:function() { /* ... */ }
}
});
</code></pre><br><br>
来源:https://www.cnblogs.com/smzd/p/11910475.html
頁:
[1]