AngularJS Store
v4.0.5
Search…
⌃K

Listen on state changes

To listen on state changes, you need to attach a "hook" in the store using the hook method. The hook will trigger depending on what action query you passed in it.
To see that in action, here is the simple example of a hook that queries the actions INCREMENT_COUNT and DECREMENT_COUNT.
your-controller.js
import { CounterStore } from 'counter-store';
function YourController($scope, counterStore) {
counterStore.hook('INCREMENT_COUNT', (state) => {
$scope.count = state.count;
});
counterStore.hook('DECREMENT_COUNT', ({ count }) => {
$scope.count = count;
});
}
angular
.module('App', [])
.controller('YourController', YourController);
All the attached hook has an initial phase which makes its callback to run automatically after successfully registered.
To check if the hook callback is currently running on its initial phase, you can use the second argument from the callback function which determines if it is an initial phase.
As you can notice in the first example, you update the same scope variable (which is the count) using two different hooks that listen on INCREMENT_COUNT and DECREMENT_COUNT, you can simplify that by using a wild card, array, or regular expression action query.
your-controller.js
import { CounterStore } from 'counter-store';
function YourController($scope, counterStore) {
// Using an array of action
counterStore.hook(['INCREMENT_COUNT', 'DECREMENT_COUNT'], (state) => {
$scope.count = state.count;
});
// Using a wild card
counterStore.hook('*', (state) => {
$scope.count = state.count;
});
// Using a regular expression
counterStore.hook(/^(IN|DE)CREMENT_COUNT$/, (state) => {
$scope.count = state.count;
});
}
angular
.module('App', [])
.controller('YourController', YourController);
Be careful of using wild card (*) action query. It makes the hook callback to always responds to all dispatched actions, even the one you are not expecting.