Javascript and Finite State Machine

Source: Internet
Author: User
Tags fsm

Simply put, it has three features:
Copy codeThe Code is as follows:
* The total number of States is limited.
* At any time point, it is in only one State.
* Under certain conditions, it will change from one state to another.

Its significance to JavaScript is that many objects can be written as finite state machines.

For example, a webpage has a menu element. The menu is displayed when you hover the mouse over it. When you move the mouse away, the menu is hidden. If you use the finite state machine description, there are only two States (display and hide) in this menu, and the mouse will trigger a state transition.

The code can be written as follows:

Copy codeThe Code is as follows:
Var menu = {

// Current status
CurrentState: 'hide ',

// Bind events
Initialize: function (){
Var self = this;
Self. on ("hover", self. transition );
},

// Status conversion
Transition: function (event ){
Switch (this. currentState ){
Case "hide ":
This. currentState = 'show ';
DoSomething ();
Break;
Case "show ":
This. currentState = 'hide ';
DoSomething ();
Break;
Default:
Console. log ('invalid State! ');
Break;
}
}

};

We can see that the finite state machine is written with clear logic and strong expression, which facilitates event encapsulation. The more States an object has and the more events it has, the more suitable it is to use the finite state machine.

In addition, JavaScript is a language with many asynchronous operations. The common solution is to specify callback functions. However, this can cause confusion in the code structure, difficulty in testing and debugging. The finite state machine provides a better way: It hooks asynchronous operations with object state changes. When the asynchronous operation ends, the corresponding state changes, and other operations are triggered. This solution is more logical and easier to reduce Code complexity than callback functions, event listening, publishing/subscription, and other solutions.

The following describes the function library Javascript Finite State Machine of a Finite State Machine. This database is very easy to understand and can help us better understand it, and its functions are not weak at all.

This database provides a global object StateMachine. Using the create method of this object, you can generate instances of finite state machines.

Copy codeThe Code is as follows:
Var fsm = StateMachine. create ();

A parameter object must be provided to describe the nature of an instance. For example, traffic signals (traffic lights) can be described as follows:

Copy codeThe Code is as follows:
Var fsm = StateMachine. create ({

Initial: 'green ',

Events :[
{Name: 'warn', from: 'green', to: 'yellow '},
{Name: 'stop', from: 'yellow', to: 'red '},
{Name: 'ready', from: 'red', to: 'yellow '},
{Name: 'Go', from: 'yellow', to: 'green '}
]
});

The initial state (initial) of traffic signals is green, and the events attribute is various events that trigger status changes. For example, the warn event changes the green state to the yellow state, the stop event changes the yellow state to the red state.

After an instance is generated, You can query the current status at any time.

Copy codeThe Code is as follows:
* Fsm. current: the current status is returned.
* Fsm. is (s): returns a Boolean value, indicating whether State s is in the current state.
* Fsm. can (e): returns a Boolean value indicating whether event e can be triggered in the current state.
* Fsm. cannot (e): returns a Boolean value indicating whether event e cannot be triggered in the current state.

Javascript Finite State Machine allows you to specify two callback functions for each event. Take the warn event as an example:

Copy codeThe Code is as follows:
* Onbeforewarn: triggered before the warn event occurs.
* Onafterwarn (can be abbreviated as onwarn): triggered after a warn event occurs.

At the same time, it allows you to specify two callback functions for each State. Take the green State as an example:

Copy codeThe Code is as follows:
* Onleavegreen: triggered when the green state is left.
* Onentergreen (can be abbreviated as ongreen): triggered when the green state is entered.

Assume that the warn event changes the State from green to yellow. The order of the above four types of callback functions is as follows: onbeforewarn → onleavegreen → onenteryellow → onafterwarn.

In addition to specifying a callback function for each event and status, you can also specify a common callback function for all events and statuses.

Copy codeThe Code is as follows:
* Onbeforeevent: triggered before any event occurs.
* Onleavestate: triggered when any status is left.
* Onenterstate: triggered when it enters any state.
* Onafterevent: triggered when any event ends.

If the event callback function contains asynchronous operations (such as Ajax communication with the server), we may want to wait until the asynchronous operation ends before the status changes. This requires the transition method.

Copy codeThe Code is as follows:
Fsm. onwarn = function (){
Light. fadeOut ('slow', function (){
Fsm. transition ();
});
Return StateMachine. ASYNC;
};

In the callback function of the code above, there is an asynchronous operation (light. fadeOut ). If you do not want the status to change immediately, you must have the callback function return a StateMachine. ASYNC object, indicating that the status does not change temporarily. When the asynchronous operation ends, call the transition method to change the status.

Javascript Finite State Machine also allows you to specify error handling functions, which are automatically triggered when an event in the current State is not possible.

Copy codeThe Code is as follows:
Var fsm = StateMachine. create ({
//...
Error: function (eventName, from, to, args, errorCode, errorMessage ){
Return 'event' + eventName + ':' + errorMessage;
},
//...
});

For example, if the current status is green, only the warn event may occur theoretically. If a stop event occurs, the above error processing function is triggered.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.