带有父子集合的Backbone JS Prefetch JSON

ahe*_*ick 2 json backbone.js

最初,当我的应用程序加载时,我想使用"重置"集合填充所有数据,因此我不必进行初始AJAX调用并获取数据.

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

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

McG*_*gle 7

您可以将Backbone Models或原始JSON传递到您的reset呼叫中.所以这是一个选择:

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

如果你有预先定义的模型可以使用,那么这是另一个:

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

编辑

如果你有原始的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);
Run Code Online (Sandbox Code Playgroud)

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