Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a recommended common pattern to memoize ajax calls?

I'm working with some government data published via Socrata's SODA api.

This API provides a way to retrieve rows via a REST call. The API allows limited parameterization of the query - basically you can do a full text search, and nothing else. I cannot find a way to shape the data returned - for example only return certain columns of the data.

As a result, basically I can only get all rows and all columns of each data view. This is ok, I guess, but I'd like to cache it - memoize it to use the underscore term.

Is there a pattern for memoization of ajax calls with jQuery?


EDIT: To give you an idea of what I'm talking about, here's what I'm doing currently.

function onclick(event) {
    var $t = $(event.currentTarget);
    var itemId = $t.attr('data-itemid');
    var url = getRestUrl(itemId);
    if (typeof datacache[itemId] === "undefined") {
        $.ajax({
            url       : url,
            cache     : true,
            type      : "GET",
            dataType  : "json",
            error     : function(xhr,status,error) {
                raiseError(error);
            },
            success   : function(response, arg2, xhr) {
                datacache[itemId] = response;
                doSomethingWithTheData(url, itemId);
            }});
    }
    else {
        doSomethingWithTheData(url, itemId);
    }
}

// then, doSomethingWithTheData() simply references datacache[itemId]

This seems like it's faster though I haven't measured it. What I really want to know is, is there a common pattern that does something like this, that I can employ, so that everyone who reads the code will immediately see what I'm doing??

like image 227
Cheeso Avatar asked Oct 17 '11 23:10

Cheeso


1 Answers

You might be able to do something like is done with autocomplete lookups (this is very much from memory, but you'll get the idea):

var searchCache = {}, searchXhr = null;

function Search(term) {

    if (term in searchCache) {
        return doSomethingWithTheData(searchCache[term]);
    }

    if (searchXhr != null) {
        searchXhr.abort();
    }

    searchXhr = $.ajax({
        url       : url,
        cache     : true,
        type      : "GET",
        dataType  : "json",
        error     : function(xhr, status, error) {
            raiseError(error);
        },
        success   : function(response, arg2, xhr) {
            searchCache[term] = response;
            if (xhr == searchXhr) {
                doSomethingWithTheData(response);
                searchXhr = null;
            }
        }
    });

}
like image 170
Cᴏʀʏ Avatar answered Oct 17 '22 02:10

Cᴏʀʏ