chore(checkbox): implemented destroy

This commit is contained in:
Johannes Eder 2021-07-20 11:05:55 +02:00 committed by Sarah Vaupel
parent 50a3ac1790
commit dedbab689f

View File

@ -9,43 +9,53 @@ const CHECKBOX_INITIALIZED_CLASS = 'checkbox--initialized';
selector: 'input[type="checkbox"]:not([uw-no-checkbox]), input[type="radio"]:not([uw-no-radiobox])',
})
export class Checkbox {
_element;
_wrapperEl;
constructor(element) {
if (!element) {
throw new Error('Checkbox utility cannot be setup without an element!');
}
this._element = element;
const isRadio = element.type === 'radio';
const isRadio = this._element.type === 'radio';
const box_class = isRadio ? RADIOBOX_CLASS : CHECKBOX_CLASS;
if (isRadio && element.closest('.radio-group')) {
if (isRadio && this._element.closest('.radio-group')) {
// Don't initialize radiobox, if radio is part of a group
return false;
}
if (element.classList.contains(CHECKBOX_INITIALIZED_CLASS)) {
if (this._element.classList.contains(CHECKBOX_INITIALIZED_CLASS)) {
// throw new Error('Checkbox utility already initialized!');
return false;
}
if (element.parentElement.classList.contains(box_class)) {
if (this._element.parentElement.classList.contains(box_class)) {
// throw new Error('Checkbox element\'s wrapper already has class '' + box_class + ''!');
return false;
}
const siblingEl = element.nextSibling;
const parentEl = element.parentElement;
const siblingEl = this._element.nextSibling;
const parentEl = this._element.parentElement;
const wrapperEl = document.createElement('div');
wrapperEl.classList.add(box_class);
this._wrapperEl = document.createElement('div');
this._wrapperEl.classList.add(box_class);
const labelEl = document.createElement('label');
labelEl.setAttribute('for', element.id);
wrapperEl.appendChild(element);
wrapperEl.appendChild(labelEl);
this._wrapperEl.appendChild(element);
this._wrapperEl.appendChild(labelEl);
parentEl.insertBefore(wrapperEl, siblingEl);
parentEl.insertBefore(this._wrapperEl, siblingEl);
element.classList.add(CHECKBOX_INITIALIZED_CLASS);
this._element.classList.add(CHECKBOX_INITIALIZED_CLASS);
}
destroy() {
this._wrapperEl.remove();
this._element.classList.remove(CHECKBOX_INITIALIZED_CLASS);
}
}