aboutsummaryrefslogtreecommitdiff
/**
 * This file is part of Haketilo.
 *
 * Function: Facilitate listening to (internal, self-generated) 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
 */