Answer the question
In order to leave comments, you need to log in
How to properly inherit components so as not to duplicate code?
There are two components (php+js+css): Checkbox and Switch.
The JS code of both does essentially the same thing, with the only difference being that input refers to different elements of the DOM tree:
ksf.classes.KsfCheckbox = class {
constructor( el ) {
let _this = this;
let change = new Event( 'change' );
this.el = el;
this.input = el.getElementsByClassName( 'checkbox__input' )[ 0 ];
this.value = +this.input.checked + '';
this.input.addEventListener( 'change', function() {
_this.el.dispatchEvent( change );
} );
this.el.addEventListener( 'click', function( e ) {
e.preventDefault();
toggleValue();
} );
/* Space Pressed */
this.el.addEventListener( 'keypress', function( e ) {
if ( e.which === 32 ) {
e.preventDefault();
toggleValue();
}
} );
function toggleValue() {
if ( _this.value === '0' ) {
_this.value = '1';
_this.input.checked = true;
} else {
_this.value = '0';
_this.input.checked = false;
}
}
}
setValue( value ) {
this.input.checked = !! parseInt( value );
this.value = parseInt( value ) + '';
}
getValue() {
return this.value;
}
};
ksf.classes.KsfSwitch = class {
constructor( el ) {
let _this = this;
let change = new Event( 'change' );
this.el = el;
this.input = el.getElementsByClassName( 'switch__input' )[ 0 ];
this.value = +this.input.checked + '';
this.input.addEventListener( 'change', function() {
_this.el.dispatchEvent( change );
} );
this.el.addEventListener( 'click', function( e ) {
e.preventDefault();
toggleValue();
} );
/* Space Pressed */
this.el.addEventListener( 'keypress', function( e ) {
if ( e.which === 32 ) {
e.preventDefault();
toggleValue();
}
} );
function toggleValue() {
if ( _this.value === '0' ) {
_this.value = '1';
_this.input.checked = true;
} else {
_this.value = '0';
_this.input.checked = false;
}
}
}
setValue( value ) {
this.input.checked = !! parseInt( value );
this.value = parseInt( value ) + '';
}
getValue() {
return this.value;
}
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question