5

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?

Nil Pun
  • 17,035
  • 39
  • 172
  • 294
  • 3
    What do you mean by reuse? Between page refreshes as well? – Jakub Konecki May 21 '12 at 01:35
  • A global variable is a perfectly acceptable way to do this assuming you don't need to re-use the data after page refreshes. Though using some sort of name-spacing scheme (for all of your code) is better: you'd make the variable "global" within the name-space... – nnnnnn May 21 '12 at 01:42
  • @JakubKonecki, reuse on one page. Not after refresh as refresh will trigger server request :-) – Nil Pun May 21 '12 at 01:48
  • 1
    @nilpun - than scoped variable or data- attribute is a way to go... – Jakub Konecki May 21 '12 at 01:50

3 Answers3

3

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • what's the benefit of this approach as opposed to global variable with proper name spacing – Nil Pun May 21 '12 at 11:16
  • It has only one (somewhere exposed) interface method, in my example `getData`. Everything it does you elsewise would need to do every time you need the data. What's the benefit of making the cache public? – Bergi May 21 '12 at 16:34
2

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>
Marko
  • 71,361
  • 28
  • 124
  • 158
1

You can store the object in data- attribute of some element - preferably container for the part of your page that represents your data (table, grid):

var json = {};

$('#mygrid').data('mydata', json);

You can retrieve it later

var json = $('#mygrid').data('mydata')

jQuery data() method documentation: http://api.jquery.com/data/

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
  • 1
    @JakubKonecki, isn't Data a HTML 5 attribute – Nil Pun May 21 '12 at 01:50
  • 1
    Data atributes are NOT HTML5 local storage. You could use data- attrbutes in IE4 if you wanted to. See http://stackoverflow.com/questions/2412947/do-html5-custom-data-attributes-work-in-ie-6/5696483#5696483 – Marko May 21 '12 at 01:51
  • Data attributes may officially be html5, but they have worked with older browsers back to at least IE5 days, so... Also, jQuery's `.data()` method can _retrieve_ html5-style data attributes, but it doesn't _store_ data in element attributes (it maintains its own structure internally and keeps track of the element association for you). – nnnnnn May 21 '12 at 01:53
  • data- attributes rendered in html are HTML5, but $.data() method is not HTML5. $.data() will return you any data- attributes as well, but you can store objects using data() method without HTML5 – Jakub Konecki May 21 '12 at 01:53
  • @Marko&nilpun I'm afraid you both are wrong. When you use `data` to **set** values, it uses jQuery cache, not attributes. – gdoron May 21 '12 at 01:54
  • @gdoron, when you use .data on an element it gets stored on the dom object via data- attributes. See my link above. – Marko May 21 '12 at 02:01
  • @Marko. You're wrong, please read the docs for `data`. you can't save objects in attributes, while with `data` you can. it doesn't use the attributes to **SET** values!!! – gdoron May 21 '12 at 02:05
  • 1
    @Marko - `.data()` does _not_ store on the DOM object. Your link above doesn't say that it does, and neither does the [jQuery doco for `.data()`](http://api.jquery.com/data/). If you want "proof", think about the fact that `.data()` can store (much) more than just strings... – nnnnnn May 21 '12 at 02:06
  • You're right, however it does READ the data- attributes from a DOM object. Either way, using .data() does NOT require HTML5 and is UNRELATED to local storage. So YOU CAN use it. – Marko May 21 '12 at 02:07