lacolaco
6/1/2017 - 6:49 AM

文化的な最低限度のWeb Component

文化的な最低限度のWeb Component

export class AwesomeCounter extends HTMLElement {

    constructor() {
        super();
        this.attachShadow({mode: 'open'});
        this.state = {};
    }
  
    connectedCallback() {
        this.setState({count: 0});
    }

    countUp() {
        this.setState({ count: this.state.count + 1 });
    }

    setState(newState) {
        this.state = Object.assign({}, this.state, newState);
        this.render();
    }

    render() {
        this.shadowRoot.innerHTML = `
        <style>
        .content { color: blue; }
        </style>

        <div>
            <span>Count: ${this.state.count}</span>
            <button id="countUpBtn">+1</button>
            <div class="content"><slot></slot></div>
        </div>
        `;
        this.shadowRoot.getElementById('countUpBtn').addEventListener('click', this.countUp.bind(this));
    }
}