addValueListener
The addValueListener
method registers a listener function with the Store
that will be called whenever data in a Value
changes.
addValueListener(
valueId: IdOrNull,
listener: ValueListener<Store>,
mutator?: boolean,
): string
Type | Description | |
---|---|---|
valueId | IdOrNull | |
listener | ValueListener<Store> | The function that will be called whenever data in the matching |
mutator? | boolean | An optional boolean that indicates that the listener mutates |
returns | string | A unique |
The provided listener is a ValueListener
function, and will be called with a reference to the Store
, the Id
of the Value
that changed, the new Value
value, the old Value
, and a GetValueChange
function in case you need to inspect any changes that occurred.
You can either listen to a single Value
(by specifying the Value
Id
) or changes to any Value
(by providing a null
wildcard).
Use the optional mutator parameter to indicate that there is code in the listener that will mutate Store
data. If set to false
(or omitted), such mutations will be silently ignored. All relevant mutator listeners (with this flag set to true
) are called before any non-mutator listeners (since the latter may become relevant due to changes made in the former). The changes made by mutator listeners do not fire other mutating listeners, though they will fire non-mutator listeners.
Examples
This example registers a listener that responds to any changes to a specific Value
.
import {createStore} from 'tinybase';
const store = createStore().setValues({open: true, employees: 3});
const listenerId = store.addValueListener(
'employees',
(store, valueId, newValue, oldValue, getValueChange) => {
console.log('employee value changed');
console.log([oldValue, newValue]);
console.log(getValueChange('employees'));
},
);
store.setValue('employees', 4);
// -> 'employee value changed'
// -> [3, 4]
// -> [true, 3, 4]
store.delListener(listenerId);
This example registers a listener that responds to any changes to any Value
.
import {createStore} from 'tinybase';
const store = createStore().setValues({open: true, employees: 3});
const listenerId = store.addValueListener(null, (store, valueId) => {
console.log(`${valueId} value changed`);
});
store.setValue('employees', 4);
// -> 'employees value changed'
store.setValue('open', false);
// -> 'open value changed'
store.delListener(listenerId);
This example registers a listener that responds to any changes to a specific Value
, and which also mutates the Store
itself.
import {createStore} from 'tinybase';
const store = createStore().setValues({open: true, employees: 3});
const listenerId = store.addValueListener(
'employees',
(store) => store.setValue('updated', true),
true,
);
store.delValue('employees');
console.log(store.getValues());
// -> {open: true, updated: true}
store.delListener(listenerId);
Since
v3.0.0