0
0
mirror of https://github.com/sveltejs/svelte.git synced 2024-12-01 17:30:59 +01:00

add combineStores function

This commit is contained in:
Rich Harris 2017-11-25 13:21:55 -05:00
parent f23c886b6a
commit a669dbfcd4
6 changed files with 63 additions and 6 deletions

View File

@ -78,6 +78,7 @@ assign(Store.prototype, {
}
Object.defineProperty(this._proto, key, {
enumerable: true,
get: function() {
if (store._dirty[key]) {
var values = deps.map(function(dep) {
@ -162,4 +163,24 @@ assign(Store.prototype, {
}
});
export default Store;
function combineStores(store, children) {
var updates = {};
for (const key in children) {
const child = children[key];
updates[key] = child.get();
child.onchange(state => {
var update = {};
update[key] = state;
store.set(update);
});
}
console.log('updates', updates);
store.set(updates);
return store;
}
export { Store, combineStores };

View File

@ -1,4 +1,4 @@
import Store from '../../../../store.js';
import { Store } from '../../../../store.js';
const store = new Store({
name: 'world'

View File

@ -1,4 +1,4 @@
import Store from '../../../../store.js';
import { Store } from '../../../../store.js';
class MyStore extends Store {
setFilter(filter) {

View File

@ -1,4 +1,4 @@
import Store from '../../../../store.js';
import { Store } from '../../../../store.js';
class MyStore extends Store {
setName(name) {

View File

@ -1,4 +1,4 @@
import Store from '../../../../store.js';
import { Store } from '../../../../store.js';
const store = new Store({
name: 'world'

View File

@ -1,5 +1,5 @@
import assert from 'assert';
import Store from '../../store.js';
import { Store, combineStores } from '../../store.js';
describe('store', () => {
describe('get', () => {
@ -143,4 +143,40 @@ describe('store', () => {
}, /'bar' is a read-only property/);
});
});
describe('combineStores', () => {
it('merges stores', () => {
const a = new Store({
x: 1,
y: 2
});
a.compute('z', ['x', 'y'], (x, y) => x + y);
const b = new Store({
x: 3,
y: 4
});
b.compute('z', ['x', 'y'], (x, y) => x + y);
const c = combineStores(new Store(), { a, b });
c.compute('total', ['a', 'b'], (a, b) => a.z + b.z);
assert.deepEqual(c.get(), {
a: {
x: 1,
y: 2,
z: 3
},
b: {
x: 3,
y: 4,
z: 7
},
total: 10
});
});
});
});