补全TypeScript中makeWatchedObject函数 :type PropEventSource<Type> = { on(eventName: `${string & keyof Type}Changed`, callback: (newValue: any) => void): void; }; function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type> { }
时间: 2023-04-06 09:00:24 浏览: 94
我可以回答这个问题。在TypeScript中,makeWatchedObject函数可以这样实现:
function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type> {
const listeners = new Map<string, Set<Function>>();
return new Proxy(obj, {
get(target, prop) {
if (prop === "on") {
return (eventName: string, callback: Function) => {
const eventListeners = listeners.get(eventName) || new Set<Function>();
eventListeners.add(callback);
listeners.set(eventName, eventListeners);
};
}
return target[prop];
},
set(target, prop, value) {
target[prop] = value;
const eventListeners = listeners.get(prop as string) || new Set<Function>();
eventListeners.forEach((callback) => callback(value));
return true;
},
});
}
这个函数接受一个对象作为参数,并返回一个代理对象。代理对象具有原始对象的所有属性和方法,同时还具有一个on方法,用于添加属性更改事件的监听器。当代理对象的属性被更改时,它会触发相应的事件监听器。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)