Skip to content

Instantly share code, notes, and snippets.

@codingchili
Created October 5, 2020 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingchili/cc14f67076e8da4fac48fd2112c1e2e5 to your computer and use it in GitHub Desktop.
Save codingchili/cc14f67076e8da4fac48fd2112c1e2e5 to your computer and use it in GitHub Desktop.
Example of a custom element using only platform standards.
import {Styles} from 'styles.js';
import '/component/rabbit-button.js'
import '/component/rabbit-input.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();
}
static get template() {
return `
<style>
/* including css rules from another module. */
${Styles.theme}
</style>
<div class="form-area">
<rabbit-input placeholder="search"></rabbit-input>
<rabbit-button>Submit</rabbit-button>
</div>
<div class="output-area">
<span class="hits">${this.hits.length}</span>
<slot></slot>
</div>
`;
}
render() {
this.innerHTML = SearchField.template;
this.bind();
}
query(query) {
// queries are scoped to the shadow tree = smaller, faster and unpolluted.
return this.shadowRoot.querySelector(query);
}
search() {
let query = this.input.value;
fetch(`/api/search?query=${query}`)
.then(response => response.json())
.then(json => {
this.hits = json;
// invokes field setter on the slotted element which can re-render.
this.slot.hits = this.hits;
})
.catch(e => alert(e));
}
bind() {
this.button = this.query('rabbit-input');
this.input = this.query('rabbit-button');
this.slot = this.query('slot').assignedNodes[0];
this.button.addEventListener('click', this.search.bind(this));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment