Html Element Attached To Js Object
I just stater a bit of OOJS but I can't get my head around one thing, making an object for and HTML element and adding events to it. For practice sake I had an idea to make inputs
Solution 1:
Use bind
function to define scope your function will use. Currently your scope is your element, not your class instance.
this.input.addEventListener('focus', this.onFocus_.bind(this));
(function(){
'use strict';
varInput = functionInput(elem) {
this.element = elem;
this.construct();
};
Input.prototype.Classes = {
INPUT: 'input-field__input',
LABEL: 'input-field__label',
EDITED: 'input-field--edited',
FOCUSED: 'input-field--focused'
};
Input.prototype.onFocus_ = function(e) {
this.element.classList.add(this.Classes.FOCUSED);
};
Input.prototype.construct = function() {
if(this.element) {
this.input = this.element.querySelector('.' + this.Classes.INPUT);
this.label = this.element.querySelector('.' + this.Classes.LABEL);
if(this.input){
this.input.addEventListener('focus', this.onFocus_.bind(this));
}
}
}
var elements = document.querySelectorAll('.input-field');
for (var n = 0; n < elements.length; n++) {
var instance = newInput(elements[n]);
}
})()
<divclass="input-field"><labelclass="input-field__label">Name</label><inputtype="text"name="name"class="input-field__input"></div><divclass="input-field"><labelclass="input-field__label">Last</label><inputtype="text"name="last"class="input-field__input"></div>
Post a Comment for "Html Element Attached To Js Object"