@Dubrovin

Как правильно унаследовать компоненты чтобы не дублировать код?

Есть два компонента (php+js+css): Checkbox и Switch.
JS-код обоих делает по сути одно и то же, с той лишь разницей что input ссылается на разные элементы DOM-дерева:
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;
	}

};


JS-файлы компонентов лежат в разных файлах, потом клеится всё в один файл с помощью gulp concat.
Как эти компоненты правильно унаследовать в JS от какого-нибудь другого компонента (например, "toggler"), чтобы не дублировать код?
  • Вопрос задан
  • 241 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
КРАФТТЕК Санкт-Петербург
от 60 000 до 80 000 ₽
summer Ярославль
от 100 000 до 140 000 ₽