Skip to content

Instantly share code, notes, and snippets.

@olegpolyakov
Created December 31, 2019 12:21
Show Gist options
  • Save olegpolyakov/416b2d67726be8b5fde3dbc7d828c9d4 to your computer and use it in GitHub Desktop.
Save olegpolyakov/416b2d67726be8b5fde3dbc7d828c9d4 to your computer and use it in GitHub Desktop.
export default class TextField {
static DEFAULT_VALUES = {
element: undefined,
type: 'text',
placeholder: '',
required: false,
onChange: Function.prototype,
onInput: Function.prototype
}
constructor(options = TextField.DEFAULT_VALUES) {
this.options = Object.assign({}, TextField.DEFAULT_VALUES, options);
this._element = null;
this._handleChange = this._handleChange.bind(this);
this._handleInput = this._handleInput.bind(this);
this.init();
}
get element() {
return this._element;
}
get isValid() {
return this._element.validity.valid;
}
get validationMessage() {
return this._element.validationMessage;
}
init() {
const { element, type, placeholder, required } = this.options;
if (typeof element === 'string') {
this._element = document.querySelector(element);
} else if (typeof element === 'object') {
this._element = element;
} else {
this._element = document.createElement('input');
}
this._element.type = type;
this._element.placeholder = placeholder;
this._element.required = required;
this._element.addEventListener('change', this._handleChange);
this._element.addEventListener('input', this._handleInput);
}
destroy() {
this._element.removeEventListener('change', this._handleChange);
this._element.removeEventListener('input', this._handleInput);
this._element.parentNode.removeChild(this._element);
}
_handleChange(event) {
this.options.onChange(event.target.value, event);
}
_handleInput(event) {
this.options.onInput(event.target.value, event);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment