Skip to content Skip to sidebar Skip to footer

Internet Explorer 9 & Javascript Variable Scoping Issue

this code works in Chrome & Firefox but not in IE9 ... need some hints ... var obj = { data: [], json: function() { var self = this; $.getJSON('highsc

Solution 1:

Your code looks fine to me, other than that data won't be populated until the json request is done, which is NOT instant because ajax is asynchronous.

obj.json();
alert(obj.data); // []
setTimeout(function(){
    alert(obj.data); // ["foo","bar","foobar"]
},5000);

Update
I suggest adding a property to your object called request, and store the $.getJSON request in it. At that point it doesn't make sense to store the data directly on the object because you can always get it from the request.

var obj = {
    request: {done:$.noop,fail:$.noop,always:$.noop},

    json: function() {
        this.request = $.getJSON("highscore.json");
    }
};
obj.json();
// you can run the following as many times as you need to use the data.
obj.request.done(function(data){
    alert(data.splice(0));
});

just note that in it's current form you must call .json() before you can add callbacks to the request.


Post a Comment for "Internet Explorer 9 & Javascript Variable Scoping Issue"