I am trying to encapsulate an AJAX call inside of an object, and by following threads here on SO I have been able to create an object (Product
) with two properties, getval
(a function for the AJAX call) and myobj
(an object containing the results of the AJAX call). When I console log the Product
object it shows both properties with the expected attributes. However, when I console log just the Product.myobj
property it comes back undefined
. So, my first question is why am I getting an undefined? and the second is this a hacky method and is there a better approach?. Thanks from a newbie, here is my code:
var url = "http://mazihealth.com";
function callback(data) {}
var Product = {
getval: function (url, callback) {
$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent(url) + '&callback=?', function (data) {
callback($(data.contents));
});
}
};
Product.getval(url, function (data) {
Product.myobj = data.filter('div').children();
console.log(Product.myobj); //Object[5]
});
console.log(Product) //Object with 2 properties
console.log(Product.myobj); //undefined
UPDATED CODE: I fixed up the callback and now create the Product.myobj in the callback function. Is there a way to encapsulate the callback function inside the Product object to create the Product.myobj property?
var url = "http://mazihealth.com";
var Product = {getval:function(url, callback) { $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent(url) + '&callback=?', callback);
}
};
function callback(data) {
Product.myobj = $(data.contents).filter('div').children();
};
Product.getval(url, callback);
console.log(Product) //Object with 2 properties
Answer to my question found here: Using $.getJSON() with callback within a Javascript object
I refactored my code in two minutes and had exactly the result I needed.