The option cachethat you saw in the documentation relates to the browser cache.
You can implement the self-starting function template in many ways, the goal is that the function result for a specific argument ( idin your case) is calculated only once.
Since you are using an Ajax request, I would suggest you use a callback argument, for example:
var getInfo = (function () {
var cache = {};
return function (id, callback) {
if (cache[id] != null) {
callback(cache[id]);
return;
}
$.post("info.url", { "id": id }, function (data) {
cache[id] = data;
callback(data);
});
};
})();
Usage example:
getInfo(5, function (data) {
alert(data);
});
source
share