Skip to content

Instantly share code, notes, and snippets.

@orbeon
Last active October 7, 2022 00:19
Show Gist options
  • Save orbeon/a2b6cef690cafd58b3745ad57de3a5a1 to your computer and use it in GitHub Desktop.
Save orbeon/a2b6cef690cafd58b3745ad57de3a5a1 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src='./test-web-component.js'></script>
</head>
<body>
<my-web-component id="my-component-1" p1="foo"></my-web-component>
<button onclick="window.document.getElementById('my-component-1').dispatchEvent(new CustomEvent('custom', { bubbles: true, detail: 3 }));">Click me</button>
</body>
</html>
const template = document.createElement("template");
template.innerHTML = `
<div class="my-component">
Hello!
<input type="checkbox">Press me!
</div>
`;
class MyWebComponent extends HTMLElement {
constructor() {
super();
this._shadowRoot = this.attachShadow({mode: "closed"});
this._shadowRoot.appendChild(template.content.cloneNode(true));
console.log("`constructor()` called");
}
connectedCallback() {
console.log("`connectedCallback()` called");
this._shadowRoot.addEventListener("click", function (e) {
console.log("listened to click event on shadow root");
console.log(e);
});
this.addEventListener("click", function (e) {
console.log("listened to click event on component");
console.log(e);
});
this._shadowRoot.addEventListener("custom", function (e) {
console.log("listened to custom event on shadow root " + e.detail);
console.log(e);
});
this.addEventListener("custom", function (e) {
console.log("listened to custom event on component " + e.detail);
console.log(e);
});
this._shadowRoot.dispatchEvent(new CustomEvent("custom", {bubbles: true, detail: 1}));
this.dispatchEvent(new CustomEvent("custom", {bubbles: true, detail: 2}));
}
}
window.customElements.define("my-web-component", MyWebComponent);
window.document.addEventListener("click", function (e) {
console.log("listened to click event from outside");
console.log(e);
});
window.document.addEventListener("custom", function (e) {
console.log("listened to custom event from outside " + e.detail);
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment