TinyBase logoTinyBase

addHasValuesListener

The addHasValuesListener method registers a listener function with the Store that will be called when Values as a whole are added to or removed from the Store.

addHasValuesListener(
  listener: HasValuesListener<Store>,
  mutator?: boolean,
): string
TypeDescription
listenerHasValuesListener<Store>

The function that will be called whenever Values as a whole are added or removed.

mutator?boolean

An optional boolean that indicates that the listener mutates Store data.

returnsstring

A unique Id for the listener that can later be used to call it explicitly, or to remove it.

The provided listener is a HasValuesListener function, and will be called with a reference to the Store. It is also given a flag to indicate whether Values now exist (having not done previously), or do not (having done so previously).

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 Values being added or removed.

import {createStore} from 'tinybase';

const store = createStore().setValues({open: true, employees: 3});
const listenerId = store.addHasValuesListener((store, hasValues) => {
  console.log('Values ' + (hasValues ? 'added' : 'removed'));
});

store.delValues();
// -> 'Values removed'

store.setValue('employees', 4);
// -> 'Values added'

store.delListener(listenerId);

This example registers a listener that responds to Values being added or removed, and which also mutates the Store itself.

import {createStore} from 'tinybase';

const store = createStore();
const listenerId = store.addHasValuesListener(
  (store, hasValues) => store.setValue('hasValues', hasValues),
  true,
);

store.setValue('employees', 4);
console.log(store.getValues());
// -> {employees: 4, hasValues: true}

store.delListener(listenerId);

Since

v4.4.0