m15o.net lib/odc

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:

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()

SOURCE

/etc/lib/odc.js

REF

bin/echo, notes/reactive