Question

var results = (function($){
    var objData,
        callback = function (data) {
             objData = data;
        };

    function getData() {
        $.getJSON('/url', function(data){ 
            callback(data) 
        });
    }
    function updateUI(){
        console.log(objData);
    }
    return {
        get   : getData, 
        show  : updateUI,
        //put : putData
    }
})(jQuery);

results.get(); 
results.show()

Hi, I'm trying to cache some data (via ajax) and update the UI based on data I got, but the show() method is executed before the call back returns and hence objData is undefined. Wondering how to solve this issue..

Was it helpful?

Solution

Use promises / deferreds. jQuery's implementation isn't very good (last time I checked) but it's usable for simple things.

var results = (function($){
    var objData,
        callback = function (data) {
             objData = data;
        };

    function getData() {
        return $.getJSON('/url', function(data){    // added return here
            callback(data) 
        });
    }
    function updateUI(){
        console.log(objData);
    }
    return {
        get   : getData, 
        show  : updateUI,
        //put : putData
    }
})(jQuery);

results.get().done(function () { // add `done`
    results.show();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top