在TypeScript中使用代理作为object.property观察程序
我已经编写了一个排序映射类型的对象(SortedMap),它存储实现这个MapItem接口的对象在TypeScript中使用代理作为object.property观察程序,typescript,Typescript,我已经编写了一个排序映射类型的对象(SortedMap),它存储实现这个MapItem接口的对象 export interface MapItem { id: string; sort: number; index: number; } 我希望SortedMap在有人更改其内部存储中某个MapItem的sort属性时使用其集合,因此,当我看到排序发生更改时,我尝试触发一个调用。将新项添加到集合时,我希望添加某种“观察者”,以查找集合MapItem.sort属性中的更改
export interface MapItem {
id: string;
sort: number;
index: number;
}
我希望SortedMap在有人更改其内部存储中某个MapItem的sort属性时使用其集合,因此,当我看到排序发生更改时,我尝试触发一个调用。将新项添加到集合时,我希望添加某种“观察者”,以查找集合MapItem.sort属性中的更改
我想我可以按照MDN Proxy上描述的模式使用代理来实现这一点,所以编写了这个函数,当向SortedMap添加新项时调用它
private addSortChangeHandler(item: MapItem) {
let self = this;
let watcher = {
set(obj: MapItem, prop: string, value: number | string) {
switch (prop) {
case "sort":
if (value <= 0) {
obj.sort = -1
} else {
obj.sort = <number>value;
}
self.sortIndex();
break;
case "index":
obj.index = <number>value;
break;
case "id":
obj.id = <string>value;
break;
}
}
}
let proxy = new Proxy(item, watcher);
this._watcher.push(proxy);
}
private addSortChangeHandler(项目:MapItem){
让自我=这个;
让观察者={
集合(对象:MapItem,属性:string,值:number | string){
开关(道具){
案例“排序”:
如果(valueOk,我就不小心通过了。如果有人想实现类似的功能:
private addSortChangeHandler(item: MapItem): MapItem {
let self = this;
let watcher = <ProxyHandler<MapItem>>{}
watcher.set = function (target, p, value, receiver) {
switch (p) {
case "sort":
if (self._sorting) {
target.sort = <number>value; //a new item is being added
} else { //the item is already in the colleciton
if (value <= 0) {
target.sort = -1
} else {
target.sort = <number>value;
}
self.sortIndex();
}
break;
case "index":
target.index = <number>value;
break;
case "id":
target.id = <string>value;
break;
}
return true;
}
let proxy = new Proxy(item, watcher);
return proxy;
}
private addSortChangeHandler(项目:MapItem):MapItem{
让自我=这个;
让watcher={}
watcher.set=函数(目标、p、值、接收器){
开关(p){
案例“排序”:
if(自我排序){
target.sort=value;//正在添加新项
}else{//该项已在集合中
如果(值)