The classical programmer in me is in love with the public/private paradigm of OO and I am finding it very hard to give up. This has caused me to run into an issue I was hoping you can help me with.
I have a singleton object called map. There can be only one. This map contains objects called Star (it's a game). A Star looks like this:
var Star = function(id, x, y) {
this.id_ = parseInt(id);
this.x_ = parseInt(x);
this.y_ = parseInt(y);
};
In reality there a lot more arguments and properties. This is just an example.
Map is defined like this:
var map = (function() {
// public interface
return {
init: function() {
getStars();
},
stars: {} // works but publicly accessible
};
var stars = new Array(); // fail
function getStars() {
$.getJSON("ps.php?jsoncallback=?", addStars);
}
function addStars(data) {
for (var x=0, xx=data.stars.length; x<xx; x++) {
map.stars[data.stars[x].id] = new Star(
data.stars[x].id,
data.stars[x].xpos,
data.stars[x].ypos
);
}
}
})();
I think due to scope of addStars
being a callback function of $.getJSON
that it can't add the newly created star to the private variable of stars (FireBug says it is undefined and jQuery calls into abort
after it tries to add it). However if I make stars a publicly visible object then it does work, but then stars is visible from the interface which is not what I want.
How can I keep stars private and have it accessible from the JSON callback?