RadioGroup.js 1.05 KB
import template from "./RadioGroup.html";

class RadioGroup {
    props = { value: String, defaultValue: String, onChange: Function };

    state = {
        value: this.props.value || this.props.defaultValue,
        childrens: [],
    };

    template = template;

    watch = {
        value: function (newVal) {
            if (newVal !== undefined) {
                this.state.value = newVal;
                this.updateChildChecked();
            }
        },
    };

    constructor() {
        for (let i = 0; i < $element[0].childNodes.length; i++) {
            let node = $element[0].childNodes[i];
            if (node.nodeType === 3) {
                $element[0].removeChild(node);
            }
        }
    }

    updateChildChecked() {
        this.state.childrens.map(function (item) {
            item.state.checked = this.state.value === item.value;
        });
    }

    setValue(event) {
        this.state.value = event.target.value;
        this.updateChildChecked();
        this.props.onChange({
            event: event,
        });
    }
}