Skip to content

Instantly share code, notes, and snippets.

@marvinhagemeister
Forked from developit/*valoo.md
Last active July 14, 2018 20:20
Show Gist options
  • Save marvinhagemeister/03d1ac7f22e722b00801c7dfb142989b to your computer and use it in GitHub Desktop.
Save marvinhagemeister/03d1ac7f22e722b00801c7dfb142989b to your computer and use it in GitHub Desktop.
🐻 Valoo: just the bare necessities of state management. 150b / 120b. https://npm.im/valoo

🐻 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.

node_modules
package-lock.json
dist
README.md
{"name":"valoo","version":"2.0.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"}}
export default (v, cb=[]) => c => c===void 0 ? v : c.call ? cb.push(c) : cb.map(f=>f(v=c)) && v
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)
}
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 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment