除了狀態(tài)和轉(zhuǎn)換動作之外, 狀態(tài)機還可以包含任意數(shù)據(jù)和方法:
var fsm = new StateMachine({
init: 'A',
transitions: [
{ name: 'step', from: 'A', to: 'B' }
],
data: {
color: 'red'
},
methods: {
describe: function() {
console.log('I am ' + this.color);
}
}
});
fsm.state; // 'A'
fsm.color; // 'red'
fsm.describe(); // 'I am red'
數(shù)據(jù)和狀態(tài)機工廠
如果要從狀態(tài)機工廠創(chuàng)建多個實例,然后data對象將在它們之間共享。這肯定不是你想要的!若要確保每個實例獲得唯一數(shù)據(jù),應(yīng)使用一個data方法來替換:
var FSM = StateMachine.factory({
init: 'A',
transitions: [
{ name: 'step', from: 'A', to: 'B' }
],
data: function(color) { // <-- 使用一個能被每個實例調(diào)用的方法
return {
color: color
}
},
methods: {
describe: function() {
console.log('I am ' + this.color);
}
}
});
var a = new FSM('red'),
b = new FSM('blue');
a.state; // 'A'
b.state; // 'A'
a.color; // 'red'
b.color; // 'blue'
a.describe(); // 'I am red'
b.describe(); // 'I am blue'
注意:構(gòu)造每個實例時使用的參數(shù)會直接傳遞給data方法。