Skip to content

Instantly share code, notes, and snippets.

@nirlanka
Last active March 29, 2020 08:38
Show Gist options
  • Save nirlanka/59ab6177892c01512447fcd0cefaac6c to your computer and use it in GitHub Desktop.
Save nirlanka/59ab6177892c01512447fcd0cefaac6c to your computer and use it in GitHub Desktop.
Simple & clean web component inner-element handling
<!DOCTYPE html>
<html>
<body>
<x-one></x-one>
<script src="./x-one.js"></script>
</body>
</html>
class XOne extends HTMLElement {
constructor() {
super();
this._createDOM();
}
connectedCallback() {
this._onNameChange = this._onNameChange.bind(this);
this._nameEl = this.querySelector('[dom-id="x-one/name"]');
this._nameInputEl = this.querySelector('[dom-id="x-one/name-input"]');
this._nameInputEl.addEventListener('input', this._onNameChange);
// Initial state
this._onNameChange();
}
disconnectedCallback() {
this._nameInputEl.removeEventListener('input', this._onNameChange);
}
_createDOM() {
this.innerHTML = /*html*/`
<div class="x-one-wrapper">
<div class="x-one-text">
My name is
<span dom-id="x-one/name" class="x-one-name"></span>!
</div>
<div>
<input dom-id="x-one/name-input" type="text" placeholder="">
</div>
</div>
`;
}
_onNameChange(ev) {
this._nameEl.innerText = this._nameInputEl.value || '___';
}
}
customElements.define('x-one', XOne);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment