Created
October 5, 2020 11:47
-
-
Save codingchili/355b1f2eb123e6358dc60305fd0b1cb5 to your computer and use it in GitHub Desktop.
custom element demo with lit-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
import {render, html} from 'lit-html.js'; | |
import {Styles} from 'styles.js'; | |
import '/component/rabbit-button.js' | |
import '/component/rabbit-input.js' | |
import '/component/search-grid.js' | |
/** | |
* Search field is a custom element that includes a | |
* button and a text field. The component consumes | |
* a search string and produces a list of search hits. | |
* | |
* The search hits are fed into the slotted component. | |
*/ | |
class SearchField extends HTMLElement { | |
constructor() { | |
super(); | |
this.attachShadow({mode: 'open'}); | |
} | |
connectedCallback() { | |
this.render(); | |
} | |
get template() { | |
// important: use the html tagged template function for rendering | |
// this will only re-render parts that changed and escape output. | |
return html` | |
<style> | |
/* including css rules from another module. */ | |
${Styles.theme} | |
</style> | |
<div class="form-area"> | |
<rabbit-input placeholder="search"></rabbit-input> | |
<rabbit-button @click="${this.query.bind(this)}">Submit</rabbit-button> | |
</div> | |
<div class="output-area" ?hidden="${!this.hits}"> | |
<span class="hits">${this.hits.length}</span> | |
<search-grid .hits="${this.hits}"></search-grid> | |
</div> | |
`; | |
} | |
render() { | |
render(this.template, this.shadowRoot) | |
} | |
query(query) { | |
// queries are scoped to the shadow tree = smaller, faster and unpolluted. | |
return this.shadowRoot.querySelector(query); | |
} | |
search() { | |
let query = this.query('input').value; | |
fetch(`/api/search?query=${query}`) | |
.then(response => response.json()) | |
.then(json => { | |
this.hits = json; | |
this.render(); | |
}) | |
.catch(e => alert(e)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment