Skip to content

Commit

Permalink
readme updated
Browse files Browse the repository at this point in the history
  • Loading branch information
serikshaikamalov committed Jul 3, 2024
1 parent 46bee7a commit 2553884
Showing 1 changed file with 27 additions and 13 deletions.
40 changes: 27 additions & 13 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
```

0 comments on commit 2553884

Please sign in to comment.