mirror of
https://github.com/sveltejs/svelte.git
synced 2024-11-29 08:32:05 +01:00
Merge pull request #2091 from sveltejs/gh-2072
add second argument to writable
This commit is contained in:
commit
3f3803e1e4
@ -34,7 +34,8 @@ export function readable(start, value) {
|
||||
};
|
||||
}
|
||||
|
||||
export function writable(value) {
|
||||
export function writable(value, start = noop) {
|
||||
let stop;
|
||||
const subscribers = [];
|
||||
|
||||
function set(newValue) {
|
||||
@ -51,11 +52,13 @@ export function writable(value) {
|
||||
function subscribe(run, invalidate = noop) {
|
||||
const subscriber = [run, invalidate];
|
||||
subscribers.push(subscriber);
|
||||
if (subscribers.length === 1) stop = start() || noop;
|
||||
run(value);
|
||||
|
||||
return () => {
|
||||
const index = subscribers.indexOf(subscriber);
|
||||
if (index !== -1) subscribers.splice(index, 1);
|
||||
if (subscribers.length === 0) stop();
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -21,6 +21,27 @@ describe('store', () => {
|
||||
|
||||
assert.deepEqual(values, [0, 1, 2]);
|
||||
});
|
||||
|
||||
it('calls provided subscribe handler', () => {
|
||||
let called = 0;
|
||||
|
||||
const store = writable(0, () => {
|
||||
called += 1;
|
||||
return () => called -= 1;
|
||||
});
|
||||
|
||||
const unsubscribe1 = store.subscribe(() => {});
|
||||
assert.equal(called, 1);
|
||||
|
||||
const unsubscribe2 = store.subscribe(() => {});
|
||||
assert.equal(called, 1);
|
||||
|
||||
unsubscribe1();
|
||||
assert.equal(called, 1);
|
||||
|
||||
unsubscribe2();
|
||||
assert.equal(called, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readable', () => {
|
||||
|
Loading…
Reference in New Issue
Block a user