Methods
State 的核心功能是能让 object to 表现出不同的行为。这些通过 state methods 实现,并可以重写,或者作为 State
’s owner 的当前状态调用。
Dispatchers
When applied to an owner object by calling state()
, State first identifies any methods already present on the owner for which there exists at least one override somewhere within the provided state expression, and relocates these methods to the new root state. For all state methods, a special dispatcher method is then instated on the owner at the corresponding key.
The dispatcher’s job is to redirect all invocations to the owner’s current state, from which State will then locate and invoke the proper stateful implementation of the method. If no active states contain an implementation for the invoked method, the invocation will be forwarded to the owner’s original implementation of the method, if one exists, or will cause a noSuchMethod
event otherwise.
Method context
By default, state methods are invoked just like normal methods, in the context of the receiving owner.
However, certain methods may require awareness of the State
from which it is called, for example, to delegate to a superstate’s implementation of a method. This can be expressed by wrapping a method’s function expression in a call to state.bind
, which causes the method to be invoked in the context of the receiving State
instead of the receiving owner. This exposes reliable references to this.superstate
, this.root
, and any other relative location in the receiving owner’s state tree, along with, importantly, the owner itself via this.owner
.
In this way delegation to a superstate’s method is facilitated by the apply
and call
methods of State
: