christiannwamba
7/6/2018 - 6:14 PM

 Valoo: just the bare necessities of state management. 150b / 120b. https://npm.im/valoo

 Valoo: just the bare necessities of state management. 150b / 120b. https://npm.im/valoo

export default function valoo(v) {
  const cb = [];
  function value(c) {
    if (arguments.length) cb.map(f => { f && f(v=c); });
    return v;
  }
  value.on = c => {
    const i = cb.push(c)-1;
    return () => { cb[i] = 0; };
  };
  return value;
}
declare module "valoo" {
  namespace valoo {
    type Disposer = () => void;
    interface Observable<T> {
      (): T;
      (value: T): void;
      on(fn: (value: T) => void): Disposer;
    }
  }

  function valoo<T = any>(value: T): valoo.Observable<T>;
  export = valoo;
}
export default (v, cb=[]) => c => {
  if (c===void 0) return v
  if (c.call) return cb.splice.bind(cb, cb.push(c)-1, 1, 0)
  v = c; for (c of cb) c && c(v)
}
export default (v, cb=[]) => c => c===void 0 ? v : c.call ? cb.push(c) : cb.map(f=>f(v=c)) && v
{
  "name": "valoo",
  "version": "2.1.0",
  "module": "valoo.mjs",
  "main": "dist/valoo.js",
  "types": "./valoo.d.ts",
  "license": "Apache-2.0",
  "scripts": {
    "prepublishOnly": "cp *valoo.md README.md;microbundle valoo.mjs"
  },
  "devDependencies": {
    "microbundle": "^0.5.1"
  }
}
node_modules
package-lock.json
dist
README.md

 valoo

just the bare necessities of state management.

Usage

Hotlink it from https://unpkg.com/valoo.

See Interactive Codepen Demo.

import valoo from 'https://unpkg.com/valoo'

// create an observable value:
const num = valoo(42)

// subscribe to value changes:
const off = num.on( v => console.log(v) )

// unsubscribe that listener:
off()

// set the value, invoking any listeners:
num(43)

// get the current value:
num()  // 43

Other Versions

  • valoo-lite.mjs: lighter 120b version, but doesn't support unsubscribing.
  • valoo-original.mjs: v1-compatible, with subscribe handled via overloading.

Credit

The idea here was first implemented in Mithril. I believe the subscription mechanism is new though.

License

Apache-2.0. Copyright 2018 Google LLC.