Can't add object to Array in jQuery's getJSON data function (scope issue)
- by seo20
I have a person object and wants to store it into a global ArrayCollection I have made.
Works great in normal scope:
var s = new ArrayCollection();
s.add(new person("Knud", "Mikkelsen", 35));
The problem is when I want to add people inside my jQuery function "mainFunction".
I can't seem to get it right. I know it's something to do with scope and I have to wrap something in functions like in my ArrayCollection.
Please help me - thanks a lot.
function ArrayCollection() {
var myArray = new Array;
return {
empty: function () {
myArray.splice(0, myArray.length);
},
add: function (myElement) {
myArray.push(myElement);
},
getAll: function () {
return myArray;
}
}
}
function person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = parseInt(parseFloat(age));
}
function mainFunction() {
//....
var s = new ArrayCollection();
s.add(new person("Knud", "Mikkelsen", 35));
$.getJSON(url, function (data) {
for (var x = 0; x < data.length; x++) {
var myPerson = new person(data[x].FirstName.toString(), data[x].LastName.toString(), data[x].Age.toString());
s.add(myPerson);
}
});
alert(drawArray(s.getAll()));
}
function drawArray(myArray) {
var v = "";
for (var i = 0; i < myArray.length; i++) {
v += myArray[i].firstName + " " + myArray[i].lastName + " (" + myArray[i].age + ")\n";
}
return v;
}