Skip to content

Commit

Permalink
feat: onUnmount
Browse files Browse the repository at this point in the history
  • Loading branch information
kt3k committed Oct 15, 2024
1 parent 3c133f3 commit ae2d119
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
9 changes: 8 additions & 1 deletion mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,8 @@ export interface Context<EL = HTMLElement> {
type: T,
handler: EventHandler<T>,
): void
/** Registers the unmount event listner */
onUnmount(handler: () => void): void
/** Queries elements by the given selector under the component dom */
query<T extends HTMLElement = HTMLElement>(selector: string): T | null
/** Queries all elements by the given selector under the component dom */
Expand Down Expand Up @@ -282,10 +284,15 @@ export function register<EL extends HTMLElement>(
}, { once: true })
}

const onUnmount = (handler: () => void) => {
el.addEventListener(`__unmount__:${name}`, handler, { once: true })
}

const context = {
el,
on,
onOutside,
onUnmount,
query: <T extends HTMLElement = HTMLElement>(s: string) =>
el.querySelector(s) as T | null,
queryAll: <T extends HTMLElement = HTMLElement>(s: string) =>
Expand Down Expand Up @@ -412,7 +419,7 @@ export function mount(name?: string | null, el?: HTMLElement) {
* @param name The component name to unmount.
* @param el The element of the component to unmount.
*/
export function unmount(name: string, el: HTMLElement) {
export function unmount(name: string, el: EventTarget) {
assert(
!!registry[name],
`The component of the given name is not registered: ${name}`,
Expand Down
31 changes: 16 additions & 15 deletions test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,25 +22,26 @@ Deno.test("Component body is called when the component is mounted", () => {
assert(called)
})

/*
Deno.test("on.__unmount__ is called when the componet is unmounted", () => {
const name = randomName();
const { on } = component(name);
Deno.test("onUnmount registers the event handler for the unmount event", () => {
const name = randomName()

document.body.innerHTML = `<div class="${name}"></div>`;
document.body.innerHTML = `<div class="${name}"></div>`

let called = false;
let called = false

on.__unmount__ = () => {
called = true;
};
function Component({ onUnmount }: Context) {
onUnmount(() => {
console.log("onUnmount called")
called = true
})
}
register(Component, name)

mount();
assert(!called);
unmount(name, query(`.${name}`)!);
assert(called);
});
*/
mount()
assert(!called)
unmount(name, document.body.firstChild!)
assert(called)
})

Deno.test("unmount removes the event listeners", () => {
const name = randomName()
Expand Down

0 comments on commit ae2d119

Please sign in to comment.