D
D
Dubrovin2018-01-31 22:51:49
JavaScript
Dubrovin, 2018-01-31 22:51:49

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;
  }

};

The JS files of the components are in different files, then everything is glued into one file using gulp concat.
How can these components be properly inherited in JS from some other component (for example, "toggler"), so as not to duplicate code?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question