這是我一直在使用的幾個生產應用程序的內容:
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";
UPDATE 裝飾實現:
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;
}
不錯!謝謝:) –
是否可以添加一個裝飾器來防止手動設置屬性的字符串值? –
@AaronUllal看看更新後的回覆。不是裝飾專家,但我試過了,它的工作原理:) –