Within a Javascript object (testObject
) I am populating an array with objects from a jQuery.getJSON
callback function. The array is defined first as an object property this.publicArray
and var passedArray = this
enables the inner callback function to access the public object.
Using a public method to the object i can expose the contents of the populated array as a child property of the object, but not the contents of the array directly.
function testObject() {
this.publicArray = [];
var passedArray = this;
$.getJSON('http://...',
function(data) {
passedArray.publicArray = [{key:'value'},{key:'value'},{key:'value'}]
});
this.testMethod = function() {
console.log(this);
console.log(this.publicArray);
};
}
myObject = new testObject(); // [1]
myObject.testMethod(); // [2]
returns:
[1] > thisArray: Array[3]
0: Object
key: "value"
1: Object
key: "value"
2: Object
key: "value"
length: 3
[2] > []
If i populate the array with exact same objects but not from a callback function it behaves as I expect it to, so I don't understand:
Thanks - and please do feel free to educate me on anything else i have screwed up.
There are a few issues with what you are trying to do.
For one, when you create the new instance of 'testObject' you are making an ajax request to populate the array property 'itsArray'. This property will have it's default value ([]) until the ajax request is complete.
Because AJAX is asynchronous by default (meaning the code will execute your 'getJSON' call and continue to the next statement immediately), any calls to 'testMethod' will return an empty array until the ajax request is complete.
What you can do is use the 'promise' that an ajax request returns (Jquery Deferred Objects) and wait for the promise to be resolved, like so:
function testObject() {
this.itsArray = [];
var passedArray = this;
this.getJSONPromise = $.getJSON('http://...',
function(data) {
passedArray.itsArray = [{key:'value'},{key:'value'},{key:'value'}]
});
this.testMethod = function() {
console.log(this);
console.log(this.itsArray);
};
}
Now that we have a 'promise' object to work with, we can wait for it to complete to call the testMethod and we will have our data.
myObject = new testObject();
$.when(myObject.getJSONPromise).then(function()
{
myObject.testMethod();
});