TinyBase logoTinyBase

addMetricListener

The addMetricListener method registers a listener function with the Metrics object that will be called whenever the value of a specified Metric changes.

addMetricListener(
  metricId: IdOrNull,
  listener: MetricListener,
): Id
TypeDescription
metricIdIdOrNull

The Id of the Metric to listen to, or null as a wildcard.

listenerMetricListener

The function that will be called whenever the Metric changes.

returnsId

A unique Id for the listener that can later be used to remove it.

You can either listen to a single Metric (by specifying the Metric Id as the method's first parameter), or changes to any Metric (by providing a null wildcard).

The provided listener is a MetricListener function, and will be called with a reference to the Metrics object, the Id of the Metric that changed, the new Metric value, and the old Metric value.

Examples

This example creates a Store, a Metrics object, and then registers a listener that responds to any changes to a specific Metric.

const store = createStore().setTable('species', {
  dog: {price: 5},
  cat: {price: 4},
  worm: {price: 1},
});

const metrics = createMetrics(store);
metrics.setMetricDefinition('highestPrice', 'species', 'max', 'price');

const listenerId = metrics.addMetricListener(
  'highestPrice',
  (metrics, metricId, newMetric, oldMetric) => {
    console.log('highestPrice metric changed');
    console.log([oldMetric, newMetric]);
  },
);

store.setCell('species', 'horse', 'price', 20);
// -> 'highestPrice metric changed'
// -> [5, 20]

metrics.delListener(listenerId);

This example creates a Store, a Metrics object, and then registers a listener that responds to any changes to any Metric.

const store = createStore().setTable('species', {
  dog: {price: 5},
  cat: {price: 4},
  worm: {price: 1},
});

const metrics = createMetrics(store)
  .setMetricDefinition('highestPrice', 'species', 'max', 'price')
  .setMetricDefinition('speciesCount', 'species');

const listenerId = metrics.addMetricListener(
  null,
  (metrics, metricId, newMetric, oldMetric) => {
    console.log(`${metricId} metric changed`);
    console.log([oldMetric, newMetric]);
  },
);

store.setCell('species', 'horse', 'price', 20);
// -> 'highestPrice metric changed'
// -> [5, 20]
// -> 'speciesCount metric changed'
// -> [3, 4]

metrics.delListener(listenerId);