Last active
March 29, 2020 08:38
-
-
Save nirlanka/59ab6177892c01512447fcd0cefaac6c to your computer and use it in GitHub Desktop.
Simple & clean web component inner-element handling
This file contains 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
<!DOCTYPE html> | |
<html> | |
<body> | |
<x-one></x-one> | |
<script src="./x-one.js"></script> | |
</body> | |
</html> |
This file contains 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
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