Subscribing with the connectTo decorator
Basic Usage
Explanation:
import { connectTo } from 'aurelia-store';
: Imports theconnectTo
decorator.@connectTo()
: This decorator automatically connects the component to the store. It creates astate
property on the component and assigns the latest state to it whenever a new state is emitted. The decorator overrides the component'sbind
andunbind
lifecycle hooks to manage the subscription to the store's state. It will also make a_stateSubscription
property available on your component where the subscription is kept and which is used during theunbind
for cleanup.
Custom Selectors
You can provide a custom selector function to connectTo
if you only want to subscribe to a specific part of the state:
Explanation:
selector: (store) => store.state.pipe(pluck('frameworks'))
: This selector function uses the RxJSpluck
operator to extract only theframeworks
property from the state.state: string[];
: Thestate
property will now only contain theframeworks
array, not the entire state object.
Multiple Selectors and Targets
You can also use multiple selectors to subscribe to different parts of the state and assign them to different properties:
Explanation:
selector: { ... }
: An object containing multiple selector functions.frameworks: (store) => ...
: Selects theframeworks
property and assigns it to theframeworks
property on the component.isLoading: (store) => ...
: Selects theisLoading
property and assigns it to theisLoading
property on the component.
You can also specify a custom target property:
When using target
with multiple selectors, the appState
property would contain an object with frameworks
and isLoading
properties.
Custom Setup and Teardown
You can customize the lifecycle methods used for setup and teardown:
Explanation:
setup: 'attached'
: The subscription will be created in theattached
lifecycle method.teardown: 'detached'
: The subscription will be disposed of in thedetached
lifecycle method.
Change Handling
The connectTo
decorator provides several ways to handle state changes:
stateChanged(newState, oldState)
: This method is called automatically when the state changes. It receives the new state and the old state as arguments.
targetChanged(newState, oldState)
: If you specify atarget
property, this method will be called instead ofstateChanged
.
onChanged: 'methodName'
: You can specify a custom method to be called when the state changes.
propertyChanged(propName, newState, oldState)
: Called after any other change handler. Receives the changed property name (or 'state' for the whole state object), the new state and the old state.
Note: The change handler methods are called before the target property is updated. This allows you to compare the new and old states and potentially make further changes.
Last updated
Was this helpful?