NAME
odc — javascript reactive primitives
SYNOPSIS
// Observable:
o = O(x)
x = o.get()
o.set(x) // no-op if deep-equal
off = o.sub((x, prev) => { ... }) // called now, then on change
off = o.sub((x, prev) => { ... }, 0) // on change only
off()
o.dis()
// Derived:
d = D(() => o.get() * 2) // deps tracked via get()
x = d.get()
off = d.sub((x, prev) => { ... })
d.dis()
// Component:
mk = C(({ obs, der, sub, tra }, ...l) => {
const o = obs(x), d = der(() => o.get() + 1)
sub(d, (x) => { ... })
tra(thing) // anything with .dis()
return { o, d }
})
c = mk(...l)
c.o.get()
c.dis() // tears down in reverse
DESCRIPTION
The odc javascript library is made of three primitives for reactive programming:
- An observable holds a value you can get, set and subscribe to.
- A component owns observables and subscriptions, and disposes them together.
- A derived is a read-only observable whose value is computed from other observables.
EXAMPLES
FizzBuzz
f = C(({ obs, der, sub }) => {
const n = obs(0),
fizz = der(() => n.get() % 3 ? '' : 'Fizz'),
buzz = der(() => n.get() % 5 ? '' : 'Buzz'),
out = der(() => fizz.get() + buzz.get() || n.get())
sub(out, s => console.log(s), 0)
return { n }
})()
f.n.set(1) // 1
f.n.set(3) // Fizz
f.n.set(15) // FizzBuzz
f.dis()