简体   繁体   English

在DOM中存储JSON的最佳实践

[英]Best practices for Storing JSON in DOM

I want to render some json data using HTML template. 我想使用HTML模板渲染一些json数据。

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). 我还没有开始实现任何东西,但我希望能够“设置”从json到html元素的数据值,其中包含一个记录的模板,或者使用一些参数来渲染一些项目集合,这些参数是模板html for每个项目,但也能够以与用于呈现项目的源JSON相同的格式返回JSON对象(我希望我的初始JSON包含有关记录行行为的更多信息,而不需要向ajax请求提供检查用户是否可以对此记录执行某些操作,并且并非所有这些信息都在模板中可见。

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". 我知道我可以使用输入元素为存储的对象的每个属性创建隐藏的表单,并将映射器函数发送到/来自JSON,但这对我来说听起来有点过分,我不喜欢它,我想要一些更轻的“信封” ”。

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)? 我想知道是否有一些JS库可以将JSON对象“序列化”和“反序列化”为html,因此我可以将它存储在DOM中的某个位置(即包含数据显示的元素,但我希望能够存储其他属性,不必显示为表单元素)?

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. 更新第一个答案建议将JSON存储在全局变量中,我也考虑过这一点,而我的“最佳”心理解决方案是制作JavaScript模块(或jQuery插件),它将JSON“映射”为html,如果不可能的话要在html中存储值,然后它可以将它们存储在内部变量中,所以当我想从html元素“获取”数据时,它可以从其本地副本中获取它。 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. 如果有一些库将这些信息存储在变量中,但是用html实时“绑定”该数据,我会非常满意。

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 更新2现在使用http://knockoutjs.com/完成,不再需要在DOM中保留json,knockout会自动执行JSON <=> HTML映射

Why not store it as nature intended: as a javascript object? 为什么不将它存储为自然意图:作为javascript对象? The DOM is a horrible place. DOM是一个可怕的地方。

That said, jQuery has the data method that allows just this. 也就是说,jQuery具有允许这样的数据方法

So you want to keep a reference to the JSON data that created your DOMFragment from a template? 那么您想要保留对从模板创建DOMFragment的JSON数据的引用吗?

Let's say you have a template function that takes a template and data and returns a DOM node. 假设您有一个模板函数,它接受模板和数据并返回一个DOM节点。

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. 您可以将原始json存储在节点的数据集上。 You may need a dataset shim though. 您可能需要一个数据集垫片。

There is also no way to "map" JSON to HTML without using a template engine. 如果不使用模板引擎,也无法将JSON“映射”到HTML。 Even then you would have to store the template name in the json data (as meta data) and that feels ugly to me. 即便如此,您还必须将模板名称存储在json数据中(作为元数据),这对我来说感觉很难看。

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. $('selector').data思想可能是最有用的技术之一。 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. 假设您有一个ajax调用,可以在页面加载时检索3篇文章。 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: 为了说明这个概念,让我们说我们检索json看起来像:

{
    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调用。 . .

$.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. 我们的想法是,我们可以将相关数据存储到dom元素,并在以后需要时访问/操作/删除该数据。 This cuts down on possible additional data calls and effectively caches data to a specific dom element. 这减少了可能的额外数据调用,并有效地将数据缓存到特定的dom元素。

anytime after the headline link is added to the document the data can be accessed through a jquery selector. 在标题链接添加到文档后的任何时候,都可以通过jquery选择器访问数据。 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. 通过选择器和jquery对象访问数据非常简单。

I don't think there are any libraries that store json in dom. 我认为没有任何库可以在dom中存储json。

You could render the html using the data from json and keep a copy of that json variable as a global variable in javascript. 您可以使用json中的数据呈现html,并将该json变量的副本保存为javascript中的全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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