/** * * @authors yutent (yutent.io@gmail.com) * @date 2020-12-08 11:30:52 * @version v1.0.0 * */ import $ from "../utils.js" import "./checkbox-item.js" export default class Checkbox extends HTMLElement { static get observedAttributes() { return ["value"] } props = { value: [] } constructor() { super(); Object.defineProperty(this, 'root', { value: this.attachShadow({ mode: 'open' }), writable: true, enumerable: false, configurable: true }) this.root.innerHTML = ` ` } _updateChildrenStat() { Array.from(this.children).forEach(it => { if (it.tagName === 'WC-CHECKBOX-ITEM' && it.root) { if (this.value.includes(it.value)) { it.checked = true } else { it.checked = false } } }) } get value() { return this.props.value } set value(val) { if (val === this.props.value) { return } this.props.value = val this._updateChildrenStat() } connectedCallback() { this._pickedFn = $.bind(this, 'child-picked', ev => { var tmp = [...this.props.value] var idx = tmp.indexOf(ev.detail.value) if (ev.detail.checked) { if (idx < 0) { tmp.push(ev.detail.value) } } else { if (~idx) { tmp.splice(idx, 1) } } this.props.value = tmp this.dispatchEvent(new CustomEvent('input')) }) } disconnectedCallback() { $.unbind(this, 'child-picked', this._pickedFn) } attributeChangedCallback(name, old, val) { if (val === null || old === val) {return} switch (name) { case 'value': if (val) { this.value = val.split(/,\s*?/) } break } } } if(!customElements.get('wc-checkbox')){ customElements.define('wc-checkbox', Checkbox) }