Add `unbox` to stores

pull/6517/head
blaumeise20 5 years ago
parent 9467e4a780
commit 1fe26ec33e

@ -411,6 +411,42 @@ import { get } from 'svelte/store';
const value = get(store);
```
#### `unbox`
```js
unbox(store, object, "property")
```
---
Unbox is a simple shorthand for assigning a store value to a property of an object. Shorthand for `store.subscribe(value => object.storeProp = value)`
```js
import { unbox } from 'svelte/store';
const object = {
storeProp: null
};
unbox(store, object, "storeProp");
```
---
It internally subscribes to the store, so you can also stop the unboxing:
```js
import { unbox } from 'svelte/store';
const object = {
storeProp: null
};
const stop = unbox(store, object, "storeProp");
stop();
```
### `svelte/motion`
@ -788,7 +824,7 @@ The `crossfade` function creates a pair of [transitions](docs#transition_fn) cal
* `delay` (`number`, default 0) — milliseconds before starting
* `duration` (`number` | `function`, default 800) — milliseconds the transition lasts
* `easing` (`function`, default `cubicOut`) — an [easing function](docs#svelte_easing)
* `fallback` (`function`) — A fallback [transition](docs#transition_fn) to use for send when there is no matching element being received, and for receive when there is no element being sent.
* `fallback` (`function`) — A fallback [transition](docs#transition_fn) to use for send when there is no matching element being received, and for receive when there is no element being sent.
```sv
<script>

@ -211,6 +211,17 @@ export function derived<T>(stores: Stores, fn: Function, initial_value?: T): Rea
});
}
/**
* "Unboxes" a store value to a property of an object.
*
* @param store - input store
* @param object - object with specified property
* @param property - a property of `object` to be assigned to
*/
export function unbox<T, K extends PropertyKey>(store: Readable<T>, object: { [X in K]: T }, property: K): Unsubscriber {
return store.subscribe(value => object[property] = value);
}
/**
* Get the current value from a store by subscribing and immediately unsubscribing.
* @param store readable

@ -1,5 +1,5 @@
import * as assert from 'assert';
import { readable, writable, derived, get } from '../../store';
import { readable, writable, derived, get, unbox } from '../../store';
describe('store', () => {
describe('writable', () => {
@ -411,4 +411,37 @@ describe('store', () => {
assert.equal(get(fake_observable), 42);
});
});
describe('unbox', () => {
it('unboxes a value', () => {
const store = writable(42);
const object = {
prop: 0
};
unbox(store, object, 'prop');
assert.equal(object.prop, 42);
store.set(123);
assert.equal(object.prop, 123);
});
it('can stop unboxing', () => {
const store = writable(42);
const object = {
prop: 0
};
const stop = unbox(store, object, 'prop');
assert.equal(object.prop, 42);
store.set(123);
assert.equal(object.prop, 123);
stop();
store.set(0);
assert.equal(object.prop, 123);
});
});
});

Loading…
Cancel
Save