一次订阅多个可写对象
subscribe to multiple writables at once
我有专柜
function createCountable(initValue: number, delta:number = 1) {
const count = writable(initValue);
return {
value: count,
inc: () => count.update(n => n + delta),
dec: () => count.update(n => n - delta),
};
}
还有一家商店
function createStore() {
const cycles = createCountable(4, 1)
const cycleLength = createCountable(30, 5)
let time: string = '00:00'
//todo how to subscribe??
return {
cycles,
cycleLength,
time
}
}
每当cycles
或cycleLength
更新时,我想重新计算时间。我怎样才能在一个功能/一个订阅中处理这个问题?
或者我应该重新设计商店的架构?
我有两个可写对象的原因是因为出于维护原因我喜欢用它的修改函数来封装值,我也可以在我的更新函数中使用多态性。
您应该看看派生商店。我会这样写你的例子
const cycles = createCountable(5, 1);
const cycleLength = createCountable(30, 5);
const time = derived([cycles, cycleLength], ([$cycles, $cycleLength]) => {
return "00:00" // do whatever you like here
})
然后在你的组件中,当你更新 cycles 或 cycleLengths 时,$time 会自动更新。
我没有测试过,但我认为它有效
有关详细信息,请查看 docs。
我有专柜
function createCountable(initValue: number, delta:number = 1) {
const count = writable(initValue);
return {
value: count,
inc: () => count.update(n => n + delta),
dec: () => count.update(n => n - delta),
};
}
还有一家商店
function createStore() {
const cycles = createCountable(4, 1)
const cycleLength = createCountable(30, 5)
let time: string = '00:00'
//todo how to subscribe??
return {
cycles,
cycleLength,
time
}
}
每当cycles
或cycleLength
更新时,我想重新计算时间。我怎样才能在一个功能/一个订阅中处理这个问题?
或者我应该重新设计商店的架构?
我有两个可写对象的原因是因为出于维护原因我喜欢用它的修改函数来封装值,我也可以在我的更新函数中使用多态性。
您应该看看派生商店。我会这样写你的例子
const cycles = createCountable(5, 1);
const cycleLength = createCountable(30, 5);
const time = derived([cycles, cycleLength], ([$cycles, $cycleLength]) => {
return "00:00" // do whatever you like here
})
然后在你的组件中,当你更新 cycles 或 cycleLengths 时,$time 会自动更新。
我没有测试过,但我认为它有效
有关详细信息,请查看 docs。