0
0
mirror of https://github.com/sveltejs/svelte.git synced 2024-11-25 09:09:35 +01:00
svelte/store.mjs

82 lines
1.6 KiB
JavaScript
Raw Normal View History

import { run_all, noop, get_store_value, safe_not_equal } from './internal';
2017-11-24 18:50:12 +01:00
export function readable(value, start) {
return {
subscribe: writable(value, start).subscribe
};
}
2017-11-25 18:07:28 +01:00
export function writable(value, start = noop) {
let stop;
const subscribers = [];
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
2019-03-09 22:34:30 +01:00
if (!stop) return; // not ready
subscribers.forEach(s => s[1]());
subscribers.forEach(s => s[0](value));
}
}
function update(fn) {
set(fn(value));
}
2017-11-25 18:07:28 +01:00
2018-12-17 01:49:42 +01:00
function subscribe(run, invalidate = noop) {
const subscriber = [run, invalidate];
subscribers.push(subscriber);
if (subscribers.length === 1) stop = start(set) || noop;
2018-12-17 01:49:42 +01:00
run(value);
2018-04-15 19:09:59 +02:00
return () => {
2018-12-17 01:49:42 +01:00
const index = subscribers.indexOf(subscriber);
if (index !== -1) subscribers.splice(index, 1);
if (subscribers.length === 0) stop();
};
}
2017-11-25 20:09:41 +01:00
return { set, update, subscribe };
}
export function derived(stores, fn, initial_value) {
const single = !Array.isArray(stores);
if (single) stores = [stores];
2017-11-24 18:50:12 +01:00
2019-02-05 23:12:14 +01:00
const auto = fn.length < 2;
2018-12-17 01:49:42 +01:00
let value = {};
return readable(initial_value, set => {
let inited = false;
const values = [];
2018-12-17 01:49:42 +01:00
let pending = 0;
const sync = () => {
2018-12-17 01:49:42 +01:00
if (pending) return;
const result = fn(single ? values[0] : values, set);
if (auto) set(result);
};
2017-11-24 18:50:12 +01:00
2018-12-17 01:49:42 +01:00
const unsubscribers = stores.map((store, i) => store.subscribe(
value => {
values[i] = value;
pending &= ~(1 << i);
if (inited) sync();
},
() => {
pending |= (1 << i);
})
);
2017-11-24 18:50:12 +01:00
inited = true;
sync();
return function stop() {
run_all(unsubscribers);
};
});
}
2019-03-01 04:07:48 +01:00
export { get_store_value as get };