add combineStores function

pull/954/head
Rich Harris 8 years ago
parent f23c886b6a
commit a669dbfcd4

@ -78,6 +78,7 @@ assign(Store.prototype, {
} }
Object.defineProperty(this._proto, key, { Object.defineProperty(this._proto, key, {
enumerable: true,
get: function() { get: function() {
if (store._dirty[key]) { if (store._dirty[key]) {
var values = deps.map(function(dep) { 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 };

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

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

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

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

@ -1,5 +1,5 @@
import assert from 'assert'; import assert from 'assert';
import Store from '../../store.js'; import { Store, combineStores } from '../../store.js';
describe('store', () => { describe('store', () => {
describe('get', () => { describe('get', () => {
@ -143,4 +143,40 @@ describe('store', () => {
}, /'bar' is a read-only property/); }, /'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
});
});
});
}); });

Loading…
Cancel
Save