简体   繁体   中英

Best practices for Storing JSON in DOM

I want to render some json data using HTML template.

I haven't started implementing anything yet, but I would like to be able to "set" values of data from json to html element which contains template for one record, or to render some collection of items using some argument which is template html for each item, but also to be able to get JSON object back in same format as source JSON which was used to render item (I want my initial JSON to contain some more information about behavior of record row, without the need to make ajax request to check if user can or can't do something with this record, and not all of this info is visible in template).

I know that I could make hidden form with an input element for each property of object to store, and mapper function to/from JSON, but it sounds like overkill to me, and I don't like that, I want some lighter "envelope".

I was wondering is there some JS library that can "serialize" and "deserialize" JSON objects into html so I can store it somewhere in DOM (ie in element which contains display for data, but I want to be able to store additional attributes which don't have to be shown as form elements)?

UPDATE As first answer suggested storing JSON in global variable, I also have thought about that, and my "best" mental solution was to make JavaScript module (or jQuery plugin) which would do "mapping" of JSON to html, and if not possible to store values in html then it can store them in internal variable, so when I want to "get" data from html element it can pull it from its local copy. I want to know is there better way for this? If there is some library that stores this info in variable, but does real-time "binding" of that data with html, I would be very happy with that.

UPDATE 2 This is now done using http://knockoutjs.com/ , no need to keep json in DOM anymore, knockout does the JSON<=>HTML mapping automatically

Why not store it as nature intended: as a javascript object? The DOM is a horrible place.

That said, jQuery has the data method that allows just this.

So you want to keep a reference to the JSON data that created your DOMFragment from a template?

Let's say you have a template function that takes a template and data and returns a DOM node.

var node = template(tmpl, json);
node.dataset.origJson = json;
node.dataset.templateName = tmpl.name;

You can store the original json on the dataset of a node. You may need a dataset shim though.

There is also no way to "map" JSON to HTML without using a template engine. Even then you would have to store the template name in the json data (as meta data) and that feels ugly to me.

I have done this in the past as well in a couple of different ways.

The $('selector').data idea is probably one of the most useful techniques. I like this way of storing data because I can store the data in a logical, intuitive and orderly fashion.

Let's say you have an ajax call that retrieves 3 articles on page load. The articles may contain data relating to the headline, the date/time, the source etc. Let's further assume you want to show the headlines and when a headline is clicked you want to show the full article and its details.

To illustrate the concept a bit let's say we retrieve json looking something like:

{
    articles: [
        {
            headline: 'headline 1 text',
            article: 'article 1 text ...',
            source: 'source of the article, where it came from',
            date: 'date of the article'
        },
        {
            headline: 'headline 2 text',
            article: 'article 2 text ...',
            source: 'source of the article, where it came from',
            date: 'date of the article'
        },
        {
            headline: 'headline 3 text',
            article: 'article 3 text ...',
            source: 'source of the article, where it came from',
            date: 'date of the article'
        }
    ]
}

From an ajax call like this . . .

$.ajax({
    url: "news/getArticles",
    data: { count: 3, filter: "popular" }, 
    success: function(data){

        // check for successful data call
        if(data.success) {

            // iterate the retrieved data
            for(var i = 0; i < data.articles.length; i++) {
                var article = data.articles[i];

                // create the headline link with the text on the headline
                var $headline = $('<a class="headline">' + article.headline + '</a>');

                // assign the data for this article's headline to the `data` property
                // of the new headline link
                $headline.data.article = article;

                // add a click event to the headline link
                $headline.click(function() {
                    var article = $(this).data.article;

                    // do something with this article data
                });

                // add the headline to the page
                $('#headlines').append($headline);
            }
        } else {
            console.error('getHeadlines failed: ', data);
        }
    }
});

The idea being we can store associated data to a dom element and access/manipulate/delete that data at a later time when needed. This cuts down on possible additional data calls and effectively caches data to a specific dom element.

anytime after the headline link is added to the document the data can be accessed through a jquery selector. To access the article data for the first headline:

$('#headlines .headline:first()').data.article.headline
$('#headlines .headline:first()').data.article.article
$('#headlines .headline:first()').data.article.source
$('#headlines .headline:first()').data.article.date

Accessing your data through a selector and jquery object is sorta neat.

I don't think there are any libraries that store json in dom.

You could render the html using the data from json and keep a copy of that json variable as a global variable in javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM