写 GUI 的时候为了维护界面的状态一直用 OOP ,但是开发的很慢,也容易出 Bug ,然后就用状态机来实现,感觉还不错,有这么用的小伙伴吗?
const FSM = function () {
this.states = [];
this.current = undefined;
this.enabled = true;
};
FSM.prototype.add = function (name, enter, leave, ...event_foo_pairs) {
let state = {
__name__: name,
enter: enter,
leave: leave
};
event_foo_pairs.forEach(pairs => state[pairs[0]] = pairs[1]);
this.states.push(state);
this.states.length === 1 && this.go(name);
};
FSM.prototype.go = function (name, ...var_args) {
const prev = this.states.filter(i => i.__name__ === this.current)
const can_leave = prev.map(i => i.leave()).reduce((p, n) => p && n, true);
if (can_leave) {
const next = this.states.filter(i => i.__name__ === name);
next.length === 0 && console.error('No such next jump: ', name);
this.current = name;
const ret = next.map(i => i.enter.apply(this, var_args)).reduce((p, n) => p && n, true);
return ret;
} else {
console.warn('Can\'t leave state: ', this.current);
console.warn(new Error().stack);
return false;
}
};
FSM.prototype.fire = function (event, ...var_args) {
return this.states.filter(i => i.__name__ === this.current && i.hasOwnProperty(event)).map(s => s[event]).map(i => i.apply(this, var_args));
};
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.