import { html, remove, select } from "../src/dom";
class Item {
constructor(
public text: string,
public count: number) {
}
}
class MyWidget {
private _items: Item[] = [];
private _onSelect?: (item: Item) => void;
private _element?: HTMLElement;
setItems(items: Item[]): this {
this._items = items;
this._updateItems();
return this;
}
getItems(): Item[] {
return this._items;
}
addItem(item: Item): this {
this._items.push(item);
this._updateItems();
return this;
}
removeItem(item: Item): this {
this._items = this._items.filter(i => i !== item);
this._updateItems();
return this;
}
onSelect(callback: (item: Item) => void): this {
this._onSelect = callback;
return this;
}
mount(e: HTMLElement | null): this {
if (e) {
this._element = html(`
`);
e.appendChild(this._element);
this._updateItems();
} else {
console.warn("invalit element", e);
}
return this;
}
umount(): this {
this._element && remove(this._element);
return this;
}
private _updateItems(): void {
if (this._element) {
this._element.innerHTML = "";
this._items.map(item => {
const li = html(`
${item.text}
[${item.count}]
`);
li.addEventListener("click", (e: Event) => {
e.stopPropagation();
if (this._onSelect) {
this._onSelect(item);
}
});
this._element && this._element.appendChild(li);
});
}
}
}
const myWidget = new MyWidget()
.setItems(
[
new Item("text 1", 1),
new Item("text 2", 2),
new Item("text 3", 3)
])
.onSelect(item => {
console.log("selected:", item);
const selected = select("#selected") as HTMLSpanElement;
selected.innerHTML = JSON.stringify(item);
// const l = myWidget.getItems().length;
// myWidget.addItem(new Item("text " + (l + 1), l + 1));
})
.mount(select("#container"));
console.log(myWidget);