You can create your own controllers by extending the Controller
class.
Import the Controller
class and create a new class that extends Controller
.
Create a type for the controller's constructor, and a second for the controller's state.
In the controller's constructor, super an object that matches your state type, spreading in the provided options with any additional state properties.
Add methods for manipulating state.
If desired, add alias definitions for accessing state properties.
In the example below, we create a controller that will increment and decrement a number. Its constructor takes a parameter, options
, an object with one optional property, initial
, that the constructor uses to set the initial state.value
property. Both properties are stored in state as { value: number, initial: number}
.
The increment
and decrement
methods set a new state based on the current state. The value
property is a read-only alias for state.value
. The diff
property is a read only value expressing the difference between the controller's current value and its initial value.
Example:
Assuming we've defined our controller in its own .ts
file (in our project's code folder), we could use the controller like so:
In this example, we'll assume we've created a code component, DataTable
, that displays some data passed into its data
prop. We want to fetch the data from an API endpoint, however the response includes an array of several pages
of data. Each page could be passed in as DataTable
's data
prop, however the DataTable
component should only display one page at a time.
As the component's authors, we could decide to accept an array of data objects through the data
prop and store the current page in the component's state. If we did so, however, our component would also have to contain all controls necessary for changing the current page.
Instead, we'll store this state outside of the component, so that designers using our component will be free to implement page controls however they wish. In order to help our designers, we'll also provide them with a controller for managing page state.
In our Overrides file, we could then use this controller like so:
Because we've located state outside of the component, designers can connect these overrides to whatever Frames or components that they wish.