为什么这个 javascript 状态机中的这个对象不能使用这个简单的函数 运行?

Why can't this simple function run on this object in this javascript state machine?

我正在为 node.js

使用 Stately.js 状态机

https://github.com/fschaefer/Stately.js/

我从一个简单的例子开始。

var fsm = Stately.machine({
    'START': {
        // event: function () {
        // }
    },
    'NEXT_STATE': {
        // event: function () {
        // }
    },
});

fsm.setMachineState(fsm.NEXT_STATE);

我收到错误 TypeError: fsm.setMachineState is not a function。有什么问题?

您不能从状态机外部更改状态。您需要当前状态上的事件才能更改为另一个状态。

我发现了一些 hacky 解决方案,它允许您在状态机中的 this 引用之外更改状态,以防您不想更改 fsm图书馆。

您可以定义自己的函数,而不是正常的状态转换

通过将此函数添加到每个状态

'setState': function(stateName){
  return this[stateName]
}

现在您的状态将如下所示,现在可以从状态机外部设置状态

var fsm = Stately.machine({
    'START': {
        'do_something': /* => */ 'NEXT_STATE',
        'setState': function(stateName){
            return this[stateName]
        }
    },
    'NEXT_STATE': {
        'setState': function(stateName){
            return this[stateName]
        }
    },
});

fsm.setState('YOUR_STATE_NAME');