JavaScript and finite state machine detailed knowledge _ basics

Source: Internet
Author: User
Tags fsm

Simply put, it has three features:

Copy Code code as follows:

* The total number of States (state) is limited.
* At any one time, only in a state.
* Under certain conditions, from a state transition (transition) to another state.

What it means to JavaScript is that many objects can be written in a finite state machine.

For example, there is a menu element on a Web page. When the mouse hovers, the menu is displayed, and when the mouse moves away, the menu is hidden. If you use a finite state machine description, the menu has only two states (show and hide), and the mouse triggers a state transition.

The code can be written in the following way:

Copy Code code as follows:

var menu = {

Current state
CurrentState: ' Hide ',

Binding events
Initialize:function () {
var self = this;
Self.on ("hover", self.transition);
},

State transitions
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
}
}

};

It can be seen that the finite state machine writing, logic clear, strong expression, conducive to packaging events. The more the state of an object and the more events that occur, the more appropriate to use the finite state machine.

In addition, the JavaScript language is a very much asynchronous operation of the language, the common solution is to specify a callback function, but this will cause the code structure confusion, difficult to test and debug problems. The finite state machine provides a better way to hook up the asynchronous operation with the state of the object, and when the asynchronous operation ends, the corresponding state changes occur, triggering other actions. This is logically more logical and easier to reduce the complexity of the code than callback functions, event sniffing, publish/subscribe solutions.

The following describes a library of finite state machines, JavaScript, finite, and Machine. This library is very understood, it can help us to deepen understanding, and the function is not weak at all.

The library provides a global object statemachine that can be used to generate instances of a finite state machine using the Create method of the object.

Copy Code code as follows:

var FSM = statemachine.create ();

When you build, you need to provide a parameter object that describes the nature of the instance. For example, a traffic light can be described like this:

Copy Code code 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 of traffic lights (initial) is the Green,events property is the trigger state changes of various events, such as Warn event makes Green state into yellow State, stop events make the yellow state red state and so on.

After the instance is generated, you can query the current state at any time.

Copy Code code as follows:

* Fsm.current: Returns the current state.
* Fsm.is (s): Returns a Boolean value indicating whether the state S is 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.

The Javascript finite state machine allows you to specify two callback functions for each event, taking the Warn event as an example:

Copy Code code as follows:

* Onbeforewarn: Triggered before the Warn event occurs.
* Onafterwarn (can be abbreviated to Onwarn): triggered after the Warn event occurs.

It also allows you to specify two callback functions for each state, taking the green state as an example:

Copy Code code as follows:

* Onleavegreen: triggered when leaving green.
* Onentergreen (can be abbreviated to Ongreen): triggered when entering green state.

Assuming that the warn event causes the state to change from green to yellow, the following four types of callback functions occur in the order of: Onbeforewarn→onleavegreen→onenteryellow→onafterwarn.

In addition to specifying callback functions individually for each event and state, you can also specify common callback functions for all events and states.

Copy Code code as follows:

* Onbeforeevent: Triggered before any event occurs.
* Onleavestate: triggered when leaving any state.
* Onenterstate: triggered when entering any state.
* Onafterevent: Triggered after any event is completed.

If there is an asynchronous operation in the callback function of the event (for example, Ajax communication with the server), then we may want to wait until the asynchronous operation is over, and then the state change occurs. This will take the transition method.

Copy Code code as follows:

Fsm.onwarn = function () {
Light.fadeout (' Slow ', function () {
Fsm.transition ();
});
return statemachine.async;
};

Inside the callback function of the code above, there is an asynchronous operation (Light.fadeout). If you do not want the state to change immediately, let the callback function return a Statemachine.async object, indicating that the state is temporarily unchanged, wait until the asynchronous operation is complete, and then call the transition method to make the state change.

The Javascript finite state machine also allows you to specify an error-handling function that is automatically triggered when an event occurs that is not possible for the current status.

Copy Code code as follows:

var FSM = statemachine.create ({
// ...
Error:function (EventName, from, to, args, errorcode, errormessage) {
Return ' event ' + eventName + ': ' + errormessage;
},
// ...
});

For example, the current state is green, in theory, only warn events can occur. If a Stop event occurs, the above error handler 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.