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;
}
I’m not seeing a scope issue there. Your success function for
getJSONis defined withinmainFunctionand so has access tos.mainFunctionis defined as a peer ofpersonand so has access to it.I am seeing a synchronous/asynchronous issue. Here’s the order of execution of
mainFunction:ArrayCollection.$.getJSON.ArrayCollection(Knud Mikkelsen)getJSONcall completes and adds the person objects to theArrayCollectionThis is because by default,
getJSONis asynchronous — it completes at some point in the future, not synchronously with the code where it was initiated. This is a good thing because synchronous Ajax calls lock up the browser UI completely and make for a poor user experience.Your options for actually seeing that person returned by the Ajax call are to move the alert to within the
getJSONsuccess handler, and/or to pass a callback intomainFunctionthat gets triggered by thegetJSONcompletion function, and/or pass theArrayCollectionto add to intomainFunctionand just check it for new person objects later as part of your program flow.Here are a couple of options for you:
Just move the
alertinside thegetJSONcompletion function:Or use a callback: