我正在查看 nativescript hello world typescript repo 和我遇到了一些使用 nativescript 的 observables 实现的乏味工作。
如果你看看 view model定义了你可以看到它是一个简单地扩展了 Observable
库的类。每当您为属性定义 setter
方法时,
您手动需要调用super.notifyPropertyChange("propertyName", propertyValue);
恕我直言,如果您的 View 模型具有许多属性,则此过程效率非常低且容易出错。
有没有办法自动执行此任务? (也许有一个基类告诉任何 setter notifyPropertyChange
?)
如果没有,你是如何处理这个问题的? Observable
机制还有其他实现吗?
最佳答案
这是我在几个生产应用程序中使用的内容:
import { Observable } from "data/observable";
export class ObservableModel extends Observable {
constructor() {
super();
}
public get(propertyName: string) {
return this["_" + propertyName];
}
public set(propertyName: string, value) {
if (this["_" + propertyName] === value) {
return;
}
this["_" + propertyName] = value;
this.refresh(propertyName);
}
public refresh(propertyName: string) {
super.notify({
eventName: Observable.propertyChangeEvent,
propertyName,
object: this,
value: this["_" + propertyName],
});
}
}
然后你的模型看起来像这样:
export class LoginViewModel extends ObservableModel {
get userName(): string { return this.get("userName"); }
set userName(val: string) { this.set("userName", val); }
get password(): string { return this.get("password"); }
set password(val: string) { this.set("password", val); }
}
当您需要使用您刚刚使用的值时:
const vm = new LoginViewModel();
vm.userName = "jdoe";
vm.password = "$3cr3T";
更新 装饰器实现:
export function ObservableProperty() {
return (target: Observable, propertyKey: string) => {
Object.defineProperty(target, propertyKey, {
get: function () {
return this["_" + propertyKey];
},
set: function (value) {
if (this["_" + propertyKey] === value) {
return;
}
this["_" + propertyKey] = value;
this.notify({
eventName: Observable.propertyChangeEvent,
propertyName: propertyKey,
object: this,
value,
});
},
enumerable: true,
configurable: true
});
};
}
型号:
export class LoginViewModel extends Observable {
@ObservableProperty() public userName: string;
@ObservableProperty() public password: string;
}
关于typescript - 实现可观察对象默认 setter 行为的 Nativescript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43311582/