I developed an app using a constructor/prototypes approach to build and manage few objects. Using JavaScript and jQuery, one of the prototype creates input fields on which an anonymous function is declared on the onclick event.
Inside the anonymous function, I can easily access the primary object with an outside reference (var that = this) and I'm also able to access the properties linked to the input object itself. However, my input field is built within a for() loop and I also need to retain the reccursive variable iterated by the loop (the famous "var i" we use to see).
Since the "i" value is passed as a reference, every input will always retain the last value "i" got. So I found a workaround by attributing to the input object its own "i" property.
So my question is : is this a good approach ? Or should I use another way to get this work ?
Here's the code :
// Let's create the constructor
function familly(motherName,fatherName,children) {
// We give to the properties their values
this.motherName = motherName;
this.fatherName = fatherName;
this.children = children;
}
// Then we create a prototype that creates an input field for each child
familly.prototype.createChildrenInputs = function() {
// I declare a variable that will serve as a reference to the main object (some people would name it "that")
var famillyObject = this;
// We pass into a loop all the children existing in the object property
var children = this.children;
for(var i in children) {
// We create the input field
var input = document.createElement('input');
$(input).val(i);
// !!! WORKAROUND !!! : I attach the "i" variable as a property to the input
input.i = i;
$(input).on('click', function() {
// 1. The main object is accessible through the var famillyObject
console.log(famillyObject);
// 2. The value of the element is accessible with this.value
console.log(this.value);
// !!! HOWEVER !!!
// ---------------
// 3. The var "i" will always return "2"
console.log(i);
// 4. But the var "this.i" will show the good value (0, 1 or 2), since the reference was turned into a value with the workaround
console.log(this.i);
});
document.body.appendChild(input);
}
}
var mother = 'Nancy';
var father = 'Eric';
var children = [
{
'name':'Stephan',
'gender':'male'
},
{
'name':'Lois',
'gender':'female'
},
{
'name':'Andrew',
'gender':'male'
}
];
var newFamilly = new familly(mother,father,children);
newFamilly.createChildrenInputs();