views:

56

answers:

1

I have a small jQuery script that gets information by looking at an ID.

What is the best way to prevent that the same data are requested more than once (e.g. what's the best practices for caching in jQuery)?

I have tried to use $.post and $.ajax with option "cache" set to true, but the request is being sent more than once.

Is it better to save collected data and use sets to see whether you'll have to request it or not?

Any ideas and suggestions are welcome!

If it matters, I use ASP.Net MVC on the server-side.

+3  A: 

The cache option you saw on the documentation, refers to the browser's cache.

You can implement a pattern of self-memorizing functions in many ways, the goal is that the function result for determined argument (id in your case) is only computed once.

Since you are using an Ajax request, I would suggest you to use a callback argument also, e.g.:

var getInfo = (function () {
  var cache = {}; // results will be cached in this object

  return function (id, callback) {
    if (cache[id] != null) { // if exist on cache
      callback(cache[id]);
      return;
    }
    // doesn't exists on cache, make Ajax request and cache it
    $.post("info.url", { "id": id }, function (data) { 
      cache[id] = data; // store the returned data
      callback(data);
    });
  };
})();

Example usage:

getInfo(5, function (data) {
  alert(data);
});
CMS
Beat me to it... I should stop writing long answers or write faster :) You'd want the cache var to be declared outside the function. Inside it won't be very helpful.
Ariel
Thanks @Ariel, actually the `cache` variable is outside the returned function, and it's accessible through the closure created by the self-executing function.
CMS
This is a great example of one of the best features of Javascript (closures) being used for memoization. You definitely want to keep the cache object inside a closure to prevent it from leaking into that horrible cesspool of the global scope.
Kris Walker