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,
): string
Type | Description | |
---|---|---|
metricId | IdOrNull | |
listener | MetricListener | The function that will be called whenever the |
returns | string | A unique |
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
.
import {createMetrics, createStore} from 'tinybase';
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
.
import {createMetrics, createStore} from 'tinybase';
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);
Since
v1.0.0