나는 nativescript hello world typescript repo를 살펴보고 있으며 nativescript의 Observable 구현으로 지루한 작업을하는 것을 발견했습니다.
뷰 모델 이 어떻게 정의 되어 있는지 살펴보면 단순히 Observable
라이브러리 를 확장하는 클래스임을 알 수 있습니다 . setter
속성에 대한 메서드를 정의 할 때마다 수동으로 호출해야합니다.super.notifyPropertyChange("propertyName", propertyValue);
IMHO이 절차 는 속성이 많은 뷰 모델이있는 경우 매우 비효율적이며 오류가 발생하기 쉽습니다 .
이 작업을 자동화하는 방법이 있습니까? (아마도 어떤 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;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다