Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse JSON Object

Scenario:

The MVC web page gets JSON object with lots of data. Upon click of button (there are quiet a number of buttons) I would like to reuse this JSON object and select required JSON Properties (without making a request to server).

It's not HTML5 so can't use browser local storage. At the moment I'm storing the JSON object on GLOBAL variable and reusing it.

Are there any elegant options available to store and re-use returned JSON object on client side?

like image 362
Nil Pun Avatar asked May 21 '12 01:05

Nil Pun


Video Answer


2 Answers

Just cache the data. There is no need to store the JSON in a global variable, I'm sure you'll find a place in your MVC application to scope a local variable. You will have implemented a getter function for the data with a callback. With caching, it'll look like this:

var getData = (function(){
    var cache;
    var loading = false;
    var callbacks = [];
    return function(callback) {
        if (typeof cache != "undefined")
            callback(cache);
        else {
            callbacks.push(callback);
            if (!loading) {
                loading = true;
                doSingleHeavyAjaxCall(options, function success(data) {
                    cache = data;
                    for (var cb; cb = callbacks.shift();)
                        cb(cache);
                });
            }
        }
     };
 })();

Then use getData(function callback(data){...}) as often as you want, and it will only trigger one ajax request.

like image 89
Bergi Avatar answered Sep 28 '22 12:09

Bergi


Another option to Jakubs answer is creating a global variable that you can update and retrieve as you like on the page.

Global variables get attached to the window object, so just write this in your <head> section.

<script type="text/javascript">
   window.jsonData = {};
</script>

Then wherever you're retrieving your data just update that object.

<script type="text/javascript">
    $.ajax(..., function(data) {
        window.jsonData = data;
    });
</script>

Then you can use it wherever you like in your code on that page.

<script type="text/javascript">
    console.dir(jsonData);
</script>
like image 24
Marko Avatar answered Sep 28 '22 10:09

Marko