【发布时间】:2020-05-15 11:40:16
【问题描述】:
我有一个派生商店,它必须使用过滤器的 HTML 选择来过滤条目对象。现在我引入了一个额外的过滤器存储(可观察)来强制派生存储回调在过滤器存储更改时运行。
但是当过滤器更改时,是否可以在没有过滤器存储的情况下触发下面派生存储中的回调?我需要这个额外的商店吗? 下面的代码工作正常。我很好奇。
import { writable, derived } from 'svelte/store';
import { entries } from './../stores/entries.js';
export const filter = writable({
// to update filter use: $filter.kind = ...
// or: filter.update(o => Object.assign(o, {kind: .., batchId: ...}));
batchId: 'all',
kind: 'all',
});
let list, total;
export const view = derived(
[filter, entries],
([$filter, $entries], set) => {
total = 0;
if ($entries) {
// filter by HTML selects: kind, batchId
list = Object.keys($entries.map).sort().reduce((a, key) => {
if ((['all', $entries.map[key].description.kind].includes($filter.kind))
&& (['all', $entries.map[key].parentId].includes($filter.batchId))) {
total += $entries.map[key].grossValue;
a.push($entries.map[key]);
};
return a;
}, []);
set({list, total});
};
return () => {
set(null);
};
}, null
);
更新:使用自定义存储的伪派生可写对象
import { writable, derived } from 'svelte/store';
import { entries } from './../stores/entries.js';
let list, total;
const filter = writable({batchId: 'all', kind: 'all'});
export const view = () => {
const viewDerived = derived([filter, entries],
([$filter, $entries]) => {
total = 0;
if ($entries) {
// filter by HTML selects: kind, batchId
list = Object.keys($entries.map).sort().reduce((a, key) => {
if ((['all', $entries.map[key].description.kind].includes($filter.kind))
&& (['all', $entries.map[key].parentId].includes($filter.batchId))) {
total += $entries.map[key].grossValue;
a.push($entries.map[key]);
};
return a;
}, []);
return {list, total};
} else return null;
}
);
// custom store methods
return {
subscribe: viewDerived.subscribe,
set: filter.set,
update: (obj) => filter.update(o => Object.assign(o, obj)),
reset: () => filter.set({batchId: 'all', kind: 'all'}),
};
}();
【问题讨论】:
-
这是在组件中运行吗?
derived在组件之外并不能真正工作,因为 Svelte 不会跟踪.js文件中的依赖关系。 -
商店做得很好。
标签: observable reactive-programming svelte