替换
对微软/ ReSub 的状态管理器进行反应
使用量
npm i -D @fdmg/resubstitute
创建存储
A 类 store 扩展 ReSubstitute 课。 它是一个类,你可以存储任何你想要的价值观.
通常你会执行 setters 财务报告和审定财务报表 getters 设置或从 store。 。 。 .
在设置功能中,你最后会打电话 this.trigger()。这将通知所有订阅者更改.
ThemeStore.ts
import { ReSubstitute } from '@fdmg/resubstitute';
export enum Theme {
SYSTEM = 'system',
DARK = 'dark',
LIGHT = 'light',
}
class ThemeStore extends ReSubstitute {
private _theme: Theme = Theme.SYSTEM;
setTheme(theme: Theme) {
this._theme = theme;
this.trigger();
}
getTheme() {
return this._theme;
}
}
export default new ThemeStore();
订阅
const subscriptionId = ThemeStore.subscribe(() => {
// Called whenever `this.trigger()` is called within ThemeStore.
});
// Unsubscribe from the ThemeStore
ThemeStore.unsubscribe(subscriptionId);
触发块
有时你可能想要做很多连续的更新,但你并不一定需要通知所有订阅者每个更新. 然后可以使用静态函数 ReSubstitute.pushTriggerBlock() 将一个块推入堆栈。 只要堆栈上有一个块,触发器不会导致用户被通知.
const resub = new ReSubstitute();
resub.subscribe(() => {
console.log('triggered');
});
// Add global trigger block to the stack
ReSubstitute.pushTriggerBlock();
// Add global trigger block to the stack
ReSubstitute.pushTriggerBlock();
resub.trigger(); // Nothing happens
ReSubstitute.popTriggerBlock();
resub.trigger(); // Nothing happens
ReSubstitute.popTriggerBlock();
resub.trigger(); // console.log('triggered');
绕行触发块
const resub = new ReSubstitute();
const resubBypass = new ReSubstitute(0, true);
resub.subscribe(() => {
console.log('triggered');
});
resubBypass.subscribe(() => {
console.log('bypass triggered');
});
// Add global trigger block to the stack
ReSubstitute.pushTriggerBlock();
resub.trigger(); // nothing happens
resubBypass.trigger(); // console.log('bypass triggered');
订阅特定的密钥
const resub = new ReSubstitute();
// Subscribe to global events
resub.subscribe(() => {
console.log('triggered');
});
// Subscribe only to key
resub.subscribe(() => {
console.log('only triggered by testKey');
}, 'testKey');
resub.trigger(); // console.log('triggered');
resub.trigger('testKey'); // console.log('only triggered by testKey');
// console.log('triggered');
// console.log('only triggered by testKey');
resub.trigger(['testKey', ReSubstitute.Key_All]);
被勒令停止的活动
const resubThrottled = new ReSubstitute(500);
resubThrottled.subscribe(() => {
console.log('triggered');
});
resubThrottled.trigger(); // console.log('triggered'); after 500ms
resubThrottled.trigger(); // trigger already scheduled so 2nd trigger is ignored