Last active
February 27, 2019 17:29
-
-
Save jinjor/eb9043cb18724f1a620901ab0ba5282b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class UtilizedElement extends HTMLElement { | |
protected cleaners: (() => void)[] = []; | |
protected $<E extends HTMLElement>(q: string): E { | |
return this.shadowRoot.querySelector(q); | |
} | |
protected on( | |
type: string, | |
selector: string, | |
callback: (e: Event, element: Element) => void | |
): void { | |
const handle = (e: Event) => { | |
let target = e.target as HTMLElement; | |
while (target && target !== e.currentTarget) { | |
if (target.matches(selector)) { | |
callback(e, target); | |
return; | |
} else { | |
target = target.parentElement; | |
} | |
} | |
}; | |
this.shadowRoot.addEventListener(type, handle); | |
} | |
subscribeWindow(key: string, callback: (e: Event) => void) { | |
window.addEventListener(key, callback); | |
this.cleaners.push(() => window.removeEventListener(key, callback)); | |
} | |
disconnectedCallback() { | |
for (let cleaner of this.cleaners) { | |
cleaner(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment