From df8f686fc1b3fbf7db3182fe29f104cc877f3660 Mon Sep 17 00:00:00 2001 From: PaulMaly Date: Sun, 15 Sep 2019 22:54:31 +0300 Subject: [PATCH] Few improvements 1) Passing previous value to `invalidate` callback. ```javascript store$.subscribe(value => { console.log('new value', value); }, value => { console.log('prev value', value); }); ``` 2) Custom equality checking callback passed as the third argument of `writable`. Very useful then store value is object or array. ``` const user$ = writable({}, undefined, (value, newValue) => { return value.name !== newValue.name; }); ``` --- src/runtime/store/index.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/runtime/store/index.ts b/src/runtime/store/index.ts index eb2eda5779..00527757b7 100644 --- a/src/runtime/store/index.ts +++ b/src/runtime/store/index.ts @@ -12,6 +12,9 @@ type Updater = (value: T) => T; /** Cleanup logic callback. */ type Invalidator = (value?: T) => void; +/** Equal logic callback. */ +type Comparator = (value: T, newValue: T) => boolean; + /** Start and stop notification callbacks. */ type StartStopNotifier = (set: Subscriber) => Unsubscriber | void; @@ -61,18 +64,19 @@ export function readable(value: T, start: StartStopNotifier): Readable * @param {*=}value initial value * @param {StartStopNotifier=}start start and stop notifications for subscriptions */ -export function writable(value: T, start: StartStopNotifier = noop): Writable { +export function writable(value: T, start: StartStopNotifier = noop, is_changed: Comparator = safe_not_equal): Writable { let stop: Unsubscriber; const subscribers: Array> = []; function set(new_value: T): void { - if (safe_not_equal(value, new_value)) { + if (is_changed(value, new_value)) { + let prev_value = value; value = new_value; if (stop) { // store is ready const run_queue = !subscriber_queue.length; for (let i = 0; i < subscribers.length; i += 1) { const s = subscribers[i]; - s[1](); + s[1](prev_value); subscriber_queue.push(s, value); } if (run_queue) { @@ -186,4 +190,4 @@ export function derived( * Get the current value from a store by subscribing and immediately unsubscribing. * @param store readable */ -export { get_store_value as get }; \ No newline at end of file +export { get_store_value as get };