Skip to content

Instantly share code, notes, and snippets.

@peerreynders
Created March 24, 2019 18:37
Show Gist options
  • Save peerreynders/937193d5d043ca63289ff93d52842571 to your computer and use it in GitHub Desktop.
Save peerreynders/937193d5d043ca63289ff93d52842571 to your computer and use it in GitHub Desktop.
Web Components in Action v5; Chapter 2 Your First Web Component: MyCustomTag using in page template element
<html lang="en">
<!-- file: index.html -->
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Chapter 2: Your First Web Component</title>
<style>
my-custom-tag {
background-color: blue;
padding: 20px;
display: inline-block;
color: white;
}
</style>
</head>
<body>
<my-custom-tag title="Another Title"></my-custom-tag>
<template id="my-custom-template">
<h2>My Custom Element</h2>
<button>click me</button>
</template>
<!-- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template -->
<script>
// https://developer.mozilla.org/en-US/docs/Glossary/IIFE
(function() {
const template = document.getElementById('my-custom-template')
class MyCustomTag extends HTMLElement {
constructor() {
super()
let clone = document.importNode(template.content, true)
this._title = clone.querySelector('h2')
this._button = clone.querySelector('button')
this.appendChild(clone)
// Want "this" to reference the custom element
// NOT the button that was clicked
this._click = this._click.bind(this)
}
_click(event) {
console.log('clicked ', event.target)
console.log('in ', this)
}
connectedCallback() {
if(this.hasAttribute('title')) {
this._title.textContent = this.getAttribute('title')
}
this._button.addEventListener('click', this._click);
}
disconnectedCallback() {
this._button.removeEventListener('click', this._click);
}
}
if(!window.customElements.get('my-custom-tag')) {
window.customElements.define('my-custom-tag', MyCustomTag);
}
}())
</script>
<!-- https://developers.google.com/web/fundamentals/web-components/best-practices -->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment