aboutsummaryrefslogtreecommitdiff
path: root/common/observable.js
blob: 02f1c1be0fcb0390f8ffe068eab296b79117e0e2 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
 * part of Hachette
 * Facilitate listening to events
 *
 * Copyright (C) 2021 Wojtek Kosior
 * Redistribution terms are gathered in the `copyright' file.
 */

const make = (value=undefined) => ({value, listeners: new Set()});
const subscribe = (observable, cb) => observable.listeners.add(cb);
const unsubscribe = (observable, cb) => observable.listeners.delete(cb);

const silent_set = (observable, value) => observable.value = value;
const broadcast = (observable, ...values) =>
      observable.listeners.forEach(cb => cb(...values));

function set(observable, value)
{
    const old_value = observable.value;
    silent_set(observable, value);
    broadcast(observable, value, old_value);
}

const observables = {make, subscribe, unsubscribe, broadcast, silent_set, set};

/*
 * EXPORTS_START
 * EXPORT observables
 * EXPORTS_END
 */