I'm trying to implement a Javascript cache of JSON data retrieved from API calls (adapted from here), in order to display dashboard widgets. The idea is this:
- Load the Google Chart script
- Once loaded, each dashboard widget calls a respective API to get the JSON data
- Cache the JSON data from each API call, in case two (or more) widgets use the same URL, and retrieve the same data
- Render each widget's Google chart using the cached JSON data
This is as far as I've got, but my RenderWidgetN()
functions are executing. When using Firebug, I can see the calls are made to the /api/...
URL's, and data is returned, but I can't then access it.
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
var cache = {};
function LoadOrCacheApiData(url, callback) {
if (!cache[url]) {
cache[url] = $.get(url).promise();
}
cache[url].done(callback);
}
function DisplayData() {
LoadOrCacheApiData('/api/AverageLevel?TopN=5', 'RenderWidget0');
LoadOrCacheApiData('/api/ExpiryCountNDays?DaysAhead=7', 'RenderWidget1');
LoadOrCacheApiData('/api/LoginCount?DaysPrevious=7', 'RenderWidget2');
}
google.charts.load('current', { packages: ['corechart', 'table'] });
google.charts.setOnLoadCallback(DisplayData);
function RenderWidget0() {
var d = JSON.parse(cache['/api/AverageLevel?TopN=5']);
alert(d);
// to do: render content to div
}
function RenderWidget1() {
var d = JSON.parse(cache['/api/ExpiryCountNDays?DaysAhead=7']);
alert(d);
// to do: render content to div
}
function RenderWidget2() {
var d = JSON.parse(cache['/api/LoginCount?DaysPrevious=7']);
alert(d);
// to do: render content to div
}
</script>
I've not used callbacks nor cache before, so there's probably tons of better ways to achieve this. Any advice/help would be appreciated please. I appreciate that this code could be compacted, but just want to get it working before I start this.