Skip to content

Commit

Permalink
Better way to listen to children.
Browse files Browse the repository at this point in the history
  • Loading branch information
thesoftwarephilosopher committed Aug 17, 2024
1 parent c80e014 commit e12f117
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions site/samples/sample5.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,36 +32,45 @@ class List extends EventTarget {

ul = <ul class='list' /> as HTMLUListElement;
items: Item[] = [];
itemUnlisteners = new Map<Item, () => void>();

add(text: string) {
const item = new Item(this, text);
this.items.push(item);
this.ul.append(item.li);
this.dispatchEvent(new Event('item-added'));

this.itemUnlisteners.set(item, listen(item, 'changed', () => {
this.dispatchEvent(new Event('item-toggled'));
}));

return item;
}

rem(item: Item) {
const unlisten = this.itemUnlisteners.get(item)!;
this.itemUnlisteners.delete(item);
unlisten();

this.items = this.items.filter(it => it !== item);
this.dispatchEvent(new Event('item-removed'));
}

clearDone = () => this.doneItems().forEach(it => it.remove());
invertAll = () => this.items.forEach(it => it.toggle());

itemChanged = () => this.dispatchEvent(new Event('item-toggled'));

doneItems = () => this.items.filter(it => it.done);

}

class Item {
class Item extends EventTarget {

done = false;
#checkbox = <input type='checkbox' /> as HTMLInputElement;
li;

constructor(private list: List, text: string) {
super();
this.li = (
<li class='item'>
{this.#checkbox}
Expand All @@ -81,7 +90,7 @@ class Item {
this.done = !this.done;
this.li.classList.toggle('done', this.done);
this.#checkbox.checked = this.done;
this.list.itemChanged();
this.dispatchEvent(new Event('changed'));
}

}
Expand Down Expand Up @@ -113,3 +122,8 @@ function Button(attrs: { onclick: () => void }, children: any) {
}}
>{children}</a>;
}

function listen(target: EventTarget, event: string, fn: () => void) {
target.addEventListener(event, fn);
return () => target.removeEventListener(event, fn);
}

0 comments on commit e12f117

Please sign in to comment.