class State{ constructor(color){ this.color = color } handle(context){ console.log(`turn to ${this.color} light`) //设置状态 context.setState(this) }}//主体class Context{ constructor(){ this.state = null } getState(){ return this.state } setState(state){ this.state = state }}//testlet context = new Context()let green = new State('green')console.log(context.getState())let yellow = new State('yellow')console.log(context.getState())let red = new State('red')console.log(context.getState())复制代码
DEMO库:javascript-state-machine
import StateMachine from 'javascript-state-machine'let fsm = new StateMachine({ init:'收藏', transitions:[ { name:'doStore', from:'收藏', to:'取消收藏' }, { name:'deleteStore', from:'取消收藏', to:'收藏' } ], methods:{ //监听执行收藏 onDoStore:function(){ alert('收藏成功') upateText() }, //监听取消收藏 onDeleteStore:function(){ alert('已经取消收藏') updateText() } }})let $btn = $('#btn')$btn.click(function(){ if (fsm.is('收藏')){ fsm.doStore() }else{ fsm.deleteStore() }})updateText(){ $btn.text(fsm.state)}复制代码
复制代码