aboutsummaryrefslogtreecommitdiff
path: root/common/observable.js
diff options
context:
space:
mode:
Diffstat (limited to 'common/observable.js')
-rw-r--r--common/observable.js33
1 files changed, 14 insertions, 19 deletions
diff --git a/common/observable.js b/common/observable.js
index 1fb0b0a..ab3b444 100644
--- a/common/observable.js
+++ b/common/observable.js
@@ -1,33 +1,28 @@
/**
- * part of Hachette
- * Facilitate listening to events
+ * 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.
*/
-function make()
-{
- return new Set();
-}
-
-function subscribe(observable, cb)
-{
- observable.add(cb);
-}
+const make = (value=undefined) => ({value, listeners: new Set()});
+const subscribe = (observable, cb) => observable.listeners.add(cb);
+const unsubscribe = (observable, cb) => observable.listeners.delete(cb);
-function unsubscribe(observable, cb)
-{
- observable.delete(cb);
-}
+const silent_set = (observable, value) => observable.value = value;
+const broadcast = (observable, ...values) =>
+ observable.listeners.forEach(cb => cb(...values));
-function broadcast(observable, event)
+function set(observable, value)
{
- for (const callback of observable)
- callback(event);
+ const old_value = observable.value;
+ silent_set(observable, value);
+ broadcast(observable, value, old_value);
}
-const observables = {make, subscribe, unsubscribe, broadcast};
+const observables = {make, subscribe, unsubscribe, broadcast, silent_set, set};
/*
* EXPORTS_START