The State class provides a way of defining state properties for the classes that extend it, as well as watching these properties for value changes.
The Component class already extends from State by default, besides automatically rerendering when there is a change.
If your class doesn't need to render anything it's best to extend from State directly though. That way you'll have access to its features without also inheriting logic you won't need.
The following example is a class that extends directly from State and defines a state property named
number on itself:
If you're familiar with YUI, you may recognize this feature and notice that it's very similar to how attributes are defined there. You basically just need to list all attributes you'll be using on the STATE static variable (on YUI it would be on ATTRS), and provide their configuration options, like initial value and validator. For a list of all valid options, take a look at State's docs.
Accessing and updating state
The constructor can receive a configuration object with initial values to use for its state properties. You can access or change an object's state in the same way you'd access or change any object property. Or you can also call the
setState function, which updates the properties specified by the given object.
You can also track state value changes by listening to the appropriate event.
To see all features of the State class take a look at its unit tests.
Any data passed to the constructor that has not been configured as a state property can still be accessed via
config. Changes to these properties won't be tracked, so it's usually intended for your component's options, which are only set from the outside.