jakesgordon / javascript-state-machine

A javascript finite state machine library
MIT License
8.69k stars 964 forks source link

Bug can() and cannot() #146

Closed code-beans closed 6 years ago

code-beans commented 6 years ago

given that a state has a transition where to is a function pointer the function will be executed, e.g.

{name : 'next', from : 'mystate', to : function () {
    foo();
    return 'nextState';
}} 

Now when fsm.can('next') is called, foo() will be executed which in my understanding it shouldn't. This looks related to #133 as well.

Leestex commented 6 years ago

Hi @code-beans

It seems like you are trying to use to function in an incorrect way here. The idea of having a function instead of defining an explicit target state name is useful in some cases, but by design it should not mutate any data.

In your specific case you should use lifecycle events to run the foo function.

Keep in mind that the to function should only define a target state is. It should not have any side effects, which foo() call is.

So the transition should look like this:

{ name: 'next', from: 'mystate', to: 'nextState' }

And lifecycle event handler:

onEnterNextState: function () {
  foo();
}

If you have to dynamically define a target state, you can use a function:

{
  name: 'next',
  from: 'mystate',
  to: function () {
    if (condition) {
       return 'nextState';
    } else {
       return 'anotherState';
    }
  }
}
code-beans commented 6 years ago

@Leestex I see. Thanks. Maybe this should go into the docs somewhere.