JavaScript Object state

Source: Internet
Author: User
Tags fsm

Finite state machines (finite-state machine) are a very useful model for simulating most things in the world.

Simply put, it has three characteristics:

* The total number of States (state) is limited.
* Any moment, only in one state.
* Under certain conditions, it shifts from one state (transition) to another.

What it means to JavaScript is that many objects can be written as finite state machines.

For example, there is a menu element on the page. When the mouse hovers, the menu is displayed, and when the mouse is moved, the menu is hidden. If you use the finite state machine description, which is the only two states of the menu (show and hide), the mouse will trigger a state transition.

The code can be written as follows:

    var menu={Current status CurrentState:' Hide ',Binding Event Initialize:function(){var self= This; Self.On("Hover", self. Transition);},State transition Transition:function(Event){Switch(This. currentstate){case"Hide": this. currentstate=' Show ';DoSomething();Break; Case"Show": this. currentstate= dosomething (break; Default. Log ( ' Invalid state! '          break;  } } 

It can be seen that the writing of finite state machines, logic clear, strong expression, is conducive to packaging events. The more the state of an object, the more events it takes, the more appropriate it is to use a finite state machine.

In addition, the JavaScript language is an extremely asynchronous operation of the language, the common solution is to specify a callback function, but this will cause code structure confusion, difficult to test and debugging problems. The finite state machine provides a better way to hook up the asynchronous operation to the state of the object, and when the asynchronous operation ends, a corresponding state change occurs, triggering other actions. This is more logical and easier to reduce the complexity of the code than the solution for callback functions, event snooping, publish/subscribe, and more.

The following is an introduction to the library of finite state machines (finite) JavaScript. This library is very understood, can help us to deepen understanding, and the function is not weak.

The library provides a global object StateMachine, which uses the Create method of the object to generate an instance of a finite state machine.

  var fsm = StateMachine.create();  

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

    var FSM= StateMachine.Create({Initial:' Green ', events:[{Name:' Warn ', from:' Green ', to:' Yellow '},{Name:' Stop ', from:' Yellow ', to:' Red '},{Name: ' ready ' :  ' red ' :  ' yellow ' } {name:  ' go '  ' yellow '  ' green ' 

The initial state of the traffic light (initial) is the Green,events attribute is a variety of events that trigger state changes, such as the Warn event that turns the green state into a yellow state, and the stop event makes the yellow state a red state, and so on.

Once the instance is built, you can query the current state at any time.

* Fsm.current: Returns the current state.
* Fsm.is (s): Returns a Boolean value that indicates whether the status S is the current state.
* Fsm.can (E): Returns a Boolean value that indicates 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, taking the Warn event as an example:

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

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

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

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

In addition to specifying a callback function for each event and state, you can also specify a generic callback function for all events and states.

* Onbeforeevent: Triggered before any event occurs.
* Onleavestate: Triggered when left in either state.
* Onenterstate: triggered when entering either state.
* Onafterevent: Triggered at the end of any event.

If there is an asynchronous operation in the callback function of the event (such as AJAX communication with the server), then we may want to wait until the asynchronous operation is finished before the state change occurs. This will use the transition method.

Fsm. onleavegreen=function(){light. Fadeout ( ' slow '  span class= "token keyword" >function ({fsm.    Transition}) return statemachine};  

Inside the callback function of the above code, there is an asynchronous operation (Light.fadeout). If you do not want the state to change immediately, let the callback function return Statemachine.async, indicating that the state does not change for the time being, and then call the transition method when the asynchronous operation ends, so that the state changes.

Javascript finite state machine also allows you to specify an error handler that fires automatically when an event occurs that is unlikely to occur in the current status.

    var FSM= StateMachine.Create({... error:function (Eventname , From) {return  ' event ' + eventName +  ': ' 

For example, the current state is green, and theoretically only warn events can occur. If the Stop event occurs, the above error-handling function is triggered.

The basic usage of Javascript finite state machine is the above, and a more detailed description can be found on its home page.

Original address: http://www.ruanyifeng.com/blog/2013/09/finite-state_machine_for_javascript.html

Nanyi

JavaScript Object state

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.