我有一个对象,它具有一些持久保存在 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++;
}
}
有没有更好的方法来实现这一目标?