Skip to content

Instantly share code, notes, and snippets.

@thesephist
Created May 29, 2018 15:38
Show Gist options
  • Save thesephist/167180c63e147ee336cab60cd8bf60bf to your computer and use it in GitHub Desktop.
Save thesephist/167180c63e147ee336cab60cd8bf60bf to your computer and use it in GitHub Desktop.
Polymer / WebComponents Todo Example
import {LitElement, html} from '@polymer/lit-element';
let __taskid_ref = 0;
const taskid = () => {
return __taskid_ref ++;
}
class PolyItem extends LitElement {
static get properties() {
return {
taskid: Number,
name: String,
}
}
_onRemoveClick(evt) {
this.removeCallback(this.taskid);
}
_render({taskid, name}) {
return html`
<li class="task">
${name}
<button class="removeButton" data-taskid="${taskid}" on-click="${this._onRemoveClick.bind(this)}">X</button>
</li>
`;
}
}
class PolyTodos extends LitElement {
static get properties() {
return {
tasks: Array,
}
}
constructor() {
super();
this.tasks = [{
id: taskid(),
name: 'Do things',
}];
}
_addItem(name) {
this.tasks = this.tasks.concat([{
id: taskid(),
name: name,
}]);
}
_removeItem(id) {
this.tasks = this.tasks.filter(t => t.id !== id);
}
_onInputKeyPress(evt) {
const input = this.shadowRoot.querySelector('input');
const inputVal = input.value.trim();
if (evt.keyCode === 13 && inputVal !== '') {
this._addItem(inputVal);
input.value = '';
}
}
_onAddButtonPress(evt) {
const input = this.shadowRoot.querySelector('input');
const inputVal = input.value.trim();
if (inputVal !== '') {
this._addItem(inputVal);
input.value = '';
}
}
_render({ tasks }) {
return html`
<h1>Todo</h1>
<input class="todoInput" type="text" on-keypress="${this._onInputKeyPress.bind(this)}"/>
<button class="addButton" on-click="${this._onAddButtonPress.bind(this)}">Add</button>
<ul>
${tasks.map(t => html`
<poly-item taskid="${t.id}" name="${t.name}" removeCallback="${this._removeItem.bind(this)}"></poly-item>
`)}
</ul>
`;
}
}
customElements.define('poly-item', PolyItem);
customElements.define('poly-todos', PolyTodos);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment