ifandelse / machina.js

js ex machina - finite state machines in JavaScript
http://machina-js.org/
Other
1.93k stars 147 forks source link

How to retry functions inside '_onEnter' on a same state? #125

Closed wjy617 closed 6 years ago

wjy617 commented 8 years ago

If I am in state 'green', and when entering in it, some functions will be executed, now I'd like to retry these functions, but this.transition('green') will go nowhere when already in this state. I can set up another state 'yellow', and let it transition to 'green' immediately to execute the function in 'green', but what is the best practice to do this?

ValeriyDP commented 8 years ago

As far I understand you have to create some actions within this state and execute them if your condition match. From example

.......
 green: {
            _onEnter: function() {
                this.handle('timeout');
                this.emit( "vehicles", { status: "GREEN" } );
            },
            timeout: function() {
                //someactions here
            },
            pedestrianWaiting: function() {
                this.deferUntilTransition( "green-interruptible" );
            },
            _onExit: function() {
                clearTimeout( this.timer );
            }
        },
.....
ysyyork commented 7 years ago

same question here.

ifandelse commented 6 years ago

@wjy617 so sorry for the delay (see #146). You would either need to create some other handlers within that state (as @valeriy-devpronet suggested), or transition to another state and come back. For example, if you had a green and checking state, when the right input comes to you during green, you transition to checking - validate whatever state you need to in order determine where to go next (green or red, etc.) and then when you transition back to green, it would fire the _onEnter handler again. As a general rule, if you're wanting to fire the _onEnter twice in the same state, it's an indication that you really have two separate states that you probably need to split up, or you have an input handler for that state that needs to be separated from the _onEnter