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

102 lines
1.9 KiB
JavaScript
Raw Normal View History

import { run_all, noop } from './internal';
2017-11-24 18:50:12 +01:00
export function readable(start, value) {
const subscribers = [];
let stop;
2017-11-24 18:50:12 +01:00
function set(newValue) {
if (newValue === value) return;
value = newValue;
2018-12-17 01:49:42 +01:00
subscribers.forEach(s => s[1]());
subscribers.forEach(s => s[0](value));
}
return {
2018-12-17 01:49:42 +01:00
subscribe(run, invalidate = noop) {
if (subscribers.length === 0) {
stop = start(set);
}
2018-12-17 01:49:42 +01:00
const subscriber = [run, invalidate];
subscribers.push(subscriber);
run(value);
return function() {
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 && stop();
stop = null;
2018-05-03 02:57:46 +02:00
}
};
2017-11-25 18:07:28 +01:00
}
};
}
2017-11-25 18:07:28 +01:00
export function writable(value) {
const subscribers = [];
function set(newValue) {
if (newValue === value) return;
value = newValue;
2018-12-17 01:49:42 +01:00
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);
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);
};
}
2017-11-25 20:09:41 +01:00
return { set, update, subscribe };
}
export function derive(stores, fn) {
const single = !Array.isArray(stores);
if (single) stores = [stores];
2017-11-24 18:50:12 +01:00
2018-12-17 01:49:42 +01:00
let value = {};
return readable(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 (value !== (value = result)) 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);
};
});
}