gpt4 book ai didi

json - 主干 JS 预取 JSON 与父子集合

转载 作者:行者123 更新时间:2023-12-04 20:12:40 25 4
gpt4 key购买 nike

最初,当我的应用程序加载时,我想使用集合“Reset”填充所有数据,这样我就不必执行初始 AJAX 调用并获取数据。

我有两个 Backbone 模型 2 个模型,一个博客和一个评论。一个博客有一个评论列表,这就是我的 JSON 的样子。

如何将其正确加载到 Backbone 集合中?

最佳答案

您可以将主干模型或原始 JSON 传递到您的 reset 调用中。所以这是一个选择:

collection.reset( [ { 
title: "A blog post",
comments: [
{ author: "someone" },
{ author: "someone else" }
]
}, {
title: "Another blog post"
} ] );

这是另一个,如果您有要使用的预定义模型:

collection.reset( [
new BlogModel( {
title: "A blog post",
comments: [
new CommentModel( { author: "someone" } ),
new CommentModel( { author: "someone else" } )
]
} ),
new BlogModel( {
title: "Another blog post"
} )
] );

编辑

如果您有原始 JSON 并想创建类型化模型,那么您始终可以只使用循环。假设您在“博客”之类的对象中有上述原始 JSON。

var models = [];
// iterate through the blogs in the raw JSON, and add them as BlogModels
_.each(blogs, function(blog) {
var blogModel = new BlogModel(blog);

// create each comment as a CommentModel, and add back to the BlogModel
blogModel.set("comments",
_.map(blogModel.get("comments"), function(comment) {
return new CommentModel(comment);
});
});
models.push(blogModel);
});
var collection = new Backbone.Collection();

// finally, create the collection using the models
collection.reset(models);

这是一个运行的例子:http://jsfiddle.net/8nLCs/8/

关于json - 主干 JS 预取 JSON 与父子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13658638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com