State
通过state expression 数据结构以声明的方式定义。
正式的 StateExpression
通过调用不包含owner
参数的 state()
函数创建,仅提供一个 expression
参数,还可以提供由空格分隔的 attributes。
.
在其内部, state expression 的内容根据对象的 categories 设置,其中包含 data
, methods
, events
, guards
, substates
, 和 transitions。
state() 的
expression可以根绝这些
categories形成结构化,或者可以通过类型推断来简化实现一些更加简单的缩写。
Structured state expressions
以入门的例子为基础,我们可以写一个包含明确分类的expression,包含子状态、方法、事件等。
var longformExpression = state({
methods: {
greet: function () { return "Hello."; }
},
states: {
Formal: {
methods: {
greet: function () { return "How do you do?"; }
},
events: {
enter: function () { this.wearTux(); }
}
},
Casual: {
methods: {
greet: function () { return "Hi!"; }
},
events: {
enter: function () { this.wearJeans(); }
}
}
}
});
// >>> StateExpression
Shorthand
明确的分类是很准确的,但是这样显得很冗余。所有 state()
同样接受更加简便的表达形式。效果同上面的一样。
var shorthandExpression = state({
greet: function () { return "Hello."; },
Formal: {
enter: function () { this.wearTux(); },
greet: function () { return "How do you do?"; }
},
Casual: {
enter: function () { this.wearJeans(); },
greet: function () { return "Hi!"; }
}
});
// >>> StateExpression
在这个例子中,state()
根据以下规则解释:
-
识别缺乏键名的类别 ,推断
Formal
和Casual
为状态 -
将
enter
识别为内置的事件类型,将关联的函数作为enter
事件的监听器,别且在被所在的 state 触发。
-
推断
greet
不是一个内置的事件类型,所以被认为是一个方法。
所有显示的定义可以通过简写来实现,但是要避免出现含糊不清的情况 (例如,创建一个名为 data
的状态,或者方法名叫做 enter
).
Interpreting expression input
提供给 state()
StateExpression
根据一下规则推断解释:
-
If an entry’s value is a typed
StateExpression
orTransitionExpression
, interpret it as-is, using the entry’s key as its name, or, if the entry’s value is the exportedstate
function itself, interpret it as an empty state whose name is the entry’s key. -
Otherwise, if an entry’s key is a category name, and its value is either an object or
null
, then it will be interpreted as it would in the long-form structured format. -
Otherwise, 如果键名同 built-in event type 匹配,或者值是string, 则推断值作为一个事件监听函数,, an array of event listeners, or a named transition target to be bound to that event type.
-
Otherwise, if an entry’s key matches a guard action (i.e.,
admit
,release
), interpret the value as a guard condition (or array of guard conditions). -
Otherwise, if an entry’s value is an object, interpret it as a substate whose name is the entry’s key, or if the entry’s value is a function, interpret it as a method whose name is the entry’s key.