Skip to content

Instantly share code, notes, and snippets.

@jinjor
Last active February 27, 2019 17:29
Show Gist options
  • Save jinjor/eb9043cb18724f1a620901ab0ba5282b to your computer and use it in GitHub Desktop.
Save jinjor/eb9043cb18724f1a620901ab0ba5282b to your computer and use it in GitHub Desktop.
class ConfirmButtonGroupElement extends UtilizedElement {
static get observedAttributes() {
return ["disabled"];
}
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.innerHTML = html`
${styles}
<style>
#group {
display: flex;
justify-content: flex-end;
}
button {
margin-left: 10px;
}
</style>
<div id="group">
<button id="cancel">Cancel</button>
<button id="ok">OK</button>
</div>
`;
if (this.hasAttribute("cancel")) {
const cancel = this.getAttribute("cancel");
if (cancel) {
this.$("#cancel").textContent = cancel;
}
} else {
this.$("#cancel").remove();
}
if (this.hasAttribute("ok")) {
const ok = this.getAttribute("ok");
if (ok) {
this.$("#ok").textContent = ok;
}
}
this.on("click", "#ok", e => {
this.dispatchEvent(new Event("ok", { bubbles: true }));
});
this.on("click", "#cancel", e => {
this.dispatchEvent(new Event("cancel", { bubbles: true }));
});
}
attributeChangedCallback(name: string, oldValue: string, newValue: string) {
if (name === "disabled") {
if (newValue === undefined) {
this.$("#ok").removeAttribute("disabled");
} else {
this.$("#ok").setAttribute("disabled", "");
}
}
}
}
customElements.define("confirm-button-group", ConfirmButtonGroupElement);
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