Doing with SCXML

Based on the tutorials by @thure.

Until now, we’ve written SCXML that doesn’t actually do anything. In the real world, when you transition to a new state UI elements need to be hidden or shown, or the appliance needs to sing a song, or the simulated character needs to use a different sprite. This chapter is about doing those things in SCXML.

There are a few nodes that make this happen, and we’ll introduce more later.

<datamodel> & <data>, and <assign> & <script>

The <datamodel> node with its children the <data> nodes are used to define the namespaces the statechart can use to store information and functions. The statechart can then use <assign> nodes to give those namespaces values and <script> nodes to do something with those values.

In this example we’ll focus only on using <assign> and <script> nodes inside <transition> nodes, though later we’ll describe other ways they can be used.

Here’s a statechart that defines how the user can drag and drop an object:

Click and drag the rectangle
Loading:
    State machine

    Click to show source code

    It’s important to mention that any scripting in SCXML is ECMAScript (a.k.a. JavaScript).

    <assign> uses two attributes, location and expr, which define *in which name* to store *what*, respectively. All expr attributes have to be expressions in ECMAScript, as if you were writing the right side of position = …. Notice here the expr attribute is used to define the initial value of the "position" <data> node as well as the values of both names in the <assign> nodes.

    The SCXML interpreter makes one more namespace available to us, _event. When an event is fired on the interpreter, you can also pass a payload as data (which is accessed through _event.data), so in this case we expect mousedown and mousemove to come with a payload that has two properties, x and y, and we expect mousedown to also include el.

    < Previous Page (States & Transitions)Next Page (Compound States) >