[Partten] PubSub partten & CustomEvent
PubSub is one of the most foundational patterns for reactivity. Firing an event out with publish()
allows anyone to listen to that event subscribe()
and do whatever they want in a decoupled from whatever fires that event.
type AnyFunction = (...args: any[]) => void
const pubSub = {
events: {} as Record<PropertyKey, AnyFunction[]>,
subscribe(eventName: string, callback: AnyFunction) {
if (!this.events[eventName]) {
this.events[eventName] = [];
}
this.events[eventName].push(callback);
},
publish(eventName: string, data: any) {
if (this.events[eventName]) {
this.events[eventName].forEach((callback) => callback(data));
}
}
};
pubSub.subscribe("update", (data) => console.log(data));
pubSub.publish("update", "Update payload");
This is a simplest way to fulfill basic reactitivy partten.
Note the publisher has no idea of what is listening to it, so there is no way to unsubscribe or clean up after itself with this simple implementation.
In browser, there is API for firing and subscribing to custom events. It allows you to send data along with the custom events using dispatchEvent
.
const pizzaEvent = new CustomEvent("pizzaDelivery", {
detail: {
name: "supreme"
}
})
const handler = (e: WindowEventMap['pizzaDelivery']) => console.log(e.detail.name)
window.addEventListener('pizzaDelivery', handler)
window.dispatchEvent(pizzaEvent)
window.removeEventListener('pizzaDelivery', handler)
// global.d.ts
interface PizzaDeliveryEvent {
name: string
}
interface CustomEventMap {
"pizzaDelivery": CustomEvent<PizzaDeliveryEvent>
}
interface WindowEventMap extends CustomEventMap {
}
Class Instance Custom Events: Subclassing EventTarget
We can subclass EventTarget to send out events on a class instance for our app to bind to:
class PizzaStore extends EventTarget {
constructor() {
super();
}
sendPizza(pizza: string) {
// fire event directly on the class
this.dispatchEvent<"pizzaDelivery">(new CustomEvent("pizzaDelivery", {
detail: {
name: pizza,
},
}));
}
}
const Pizzas = new PizzaStore();
const handler2 = (e: CustomEventMap["pizzaDelivery"]) => console.log('Added Pizza:', e.detail.name)
Pizzas.addEventListener("pizzaDelivery", handler2);
Pizzas.sendPizza("supreme");
Pizzas.removeEventListener("pizzaDelivery", handler2);
// global.d.ts
interface PizzaDeliveryEvent {
name: string
}
interface CustomEventMap {
"pizzaDelivery": CustomEvent<PizzaDeliveryEvent>
}
interface WindowEventMap extends CustomEventMap {
}
interface EventTarget {
dispatchEvent<EventName extends keyof CustomEventMap>(event: CustomEventMap[EventName]): boolean;
addEventListener<Type extends keyof CustomEventMap, T extends CustomEventMap[Type]>(type: Type, callback: (event: T) => void): void;
removeEventListener<Type extends keyof CustomEventMap, T extends CustomEventMap[Type]>(type: Type, callback: (event: T) => void): void;
}
The cool thing about this is your events aren’t firing globally on the window. You can fire an event directly on a class; anything in your app can wire up event listeners directly to that class.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2022-10-04 [Typescript] Tips: Create your own 'objectKeys' function using generics and the 'keyof' operator
2022-10-04 [Typescript + React] Tips: Write your own 'PropsFrom' helper to extract props from any React component
2021-10-04 [Cloud Architect] 9. Securing Access to Cloud Services
2020-10-04 [Typescript] User defined type guards
2020-10-04 [TypeScript] instanceof and Type Guards (getPrototypeOf)
2019-10-04 [Angular] How to show global loading spinner for application between page navigation
2019-10-04 [NgRx] NgRx Data Fetching Solution - How to Load Data Only If Needed