From 255388448a08a7d6cc29144084bd9a01a8183c45 Mon Sep 17 00:00:00 2001 From: Serik Date: Thu, 4 Jul 2024 01:23:55 +0500 Subject: [PATCH] readme updated --- readme.md | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/readme.md b/readme.md index c164225..92512fc 100644 --- a/readme.md +++ b/readme.md @@ -109,26 +109,40 @@ In this example: ## EventTarget as a global storage +Demo: [BasketStorage](https://serikshaikamalov.github.io/lit-components/examples/basket/index.html) + Why to use it? - A way of communication between components - Source of the truth - Implement subscriber/listener pattern -Interface +Usage ```js -interface EventTarget { - addEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: AddEventListenerOptions | boolean - ): void; - dispatchEvent(event: Event): boolean; - removeEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: EventListenerOptions | boolean - ): void; +/** + * This singleton EventEmitter can be used throughout your application to handle custom events. + */ +export class BasketStorage extends EventTarget { + items = []; + static instance; + + static getInstance() { + if (!BasketStorage.instance) { + BasketStorage.instance = new BasketStorage(); + } + return BasketStorage.instance; + } + + addItem(item) { + this.items = [...this.items, item]; + this.dispatchEvent(new CustomEvent("updated", { detail: { item } })); + } + getItems() { + return this.items; + } } + +const basketStorage = BasketStorage.getInstance(); +export default basketStorage; ```