Dan
Dan

Reputation: 1295

cache in jquery for json files

hi so I am trying to build a cache system

the way this works is that when a user clicks on a tab it loads in the json for that tab - that all works ok apart from if a user clicks multiple times on a tab it goes and fetches the json multiple times - not ideal

so my idea was to build a cache so that after the first time a tab is clicked that json is added to the cache and called from there the next time.

the problem is really where to initialize the cache array so that the function can add to it.

obviously where I have it now will mean its undefined when it tries to call the getData function. Can anyone help? here is the code

$(function() {
    var cache = {}; 
    $(".nav-tabs li a").on("click", function(){
        var tabID = $(this).attr("href");
        getData(tabID, applicationID);
    });
});

function getData(tabID, applicationID){
    tab = tabID.replace('#', '');
    var promise = this.cache[tab];

    if (!promise) {
        promise = getJSON(tab, applicationID);
        this.cache[name] = promise;
    }

    $.when(promise).then(function(result) {
    //do something!
    });

function getJSON (name, applicationID) {


    var promise =   $.ajax({
            url: 'data/' + name + '.json',
            method: 'get',
            dataType: 'json', 
            data: {appID:applicationID}
    });

    return promise;
}

Upvotes: 0

Views: 133

Answers (1)

Barmar
Barmar

Reputation: 782755

One way is to declare cache as a global variable.

Another way is to put the definitions of getData and getJSON inside $(function() {...});, so they'll be in the same scope as cache.

Upvotes: 1

Related Questions