我可以在 MobX 中手动触发特定属性的观察器吗?
Can I manually trigger observers of specific properties in MobX?
我有一个对象,它有一些可观察的属性,这些属性持久保存在cookie中:
class MyClass {
@observable attribute = Cookies.get("attribute");
@action updateAttribute(newValue) {
this.attribute = newValue;
Cookies.set("attribute", newValue);
}
}
var obj = new MyClass();
这显然不理想,因为现在我将数据保存在两个地方(属性和 cookie)。理想情况下,我很想做这样的事情:
class MyClass {
@computed get attribute() {
return Cookies.get("attribute");
}
@action updateAttribute(newValue) {
Cookies.set("attribute", newValue);
// Somehow mark the computed property `this.attribute` as dirty.
}
}
这样的解决方案可能有效:
class MyClass {
@observable _version = 0;
@computed get attribute() {
// Read `this._version` to create the dependency.
this._version;
return Cookies.get("attribute");
}
@action updateAttribute(newValue) {
Cookies.set("attribute", newValue);
this._version++;
}
}
有没有更好的方法来实现这一目标?
我认为您的解决方案实际上非常好。另一种解决方案是在启动时仅"读取"一次cookie,然后使用autorun来存储cookie:
class MyClass {
@observable attribute = Cookie.get("attribute")
constructor() {
autorun(() => Cookie.set("attribute", this.attribute))
}
}
相关文章:
- 未激发路由的控制器属性上的观察者
- Knockout observable没有观察到其中一个属性
- 将属性设置为未定义时未通知观察者
- Ember:当子控制器同时观察到父控制器触发请求的相同属性时
- 观察ES6模块属性
- 如何从具有动态可观察属性的淘汰对象中获取 JSON 字符串
- 观察多个$scope属性
- KO 绑定复选框:从代码更改“选中”属性,不更改可观察字段
- 更新挖空中可观察数组中项目的属性
- AngularJS:观察数组属性
- AngularJS观察指令属性表达式,动态继承作用域
- 聚合物通过父对象观察子属性
- 初始化可从元素属性值观察到的Knockout
- 如何使用ES6在Ember中声明可观察性或计算属性
- 如何观察聚合物元素属性值从索引.html的变化
- 当可观察数组是其他模型的属性时,挖空不会更新 UI
- 获取可观察数组项的子属性以触发更改
- 聚合物中的“观察者”与“通知”(在属性块中)与“观察者”与“侦听器”之间的区别
- 使用挖空 JS 映射选项将可观察属性添加到映射的可观察数组
- 余烬在加载时观察到异步属于关系属性