带有父子集合的Backbone JS Prefetch JSON

时间:2012-12-01 10:44:59

标签: json backbone.js

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

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

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

2 个答案:

答案 0 :(得分:7)

您可以将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/

答案 1 :(得分:0)

我会做这样的事情:

var CommentsCollection
  , PostModel
  , PostsCollection
  , posts
  , blogData;


CommentsCollection = Backbone.Collection.extend({});


PostModel = Backbone.Model.extend({

  initialize: function() {
    this.comments = new CommentsCollection;
    this.comments.post = this;
    this.on("change:comments", this.updateComments);
    this.updateComments();
  },

  updateComments: function() {
    this.comments.reset(this.get("comments"));
  }

});

PostsCollection = Backbone.Collection.extend({
  model: PostModel
});

blogData = [
  {
    id: 1,
    title: "My Post1",
    comments: [
      {id: 1, message: "Test message 1"},
      {id: 2, message: "Test message 2"}
    ]
  },

  {
    id: 2,
    title: "My Post 2",
    comments: [
      {id: 3, message: "Test message 3"},
      {id: 4, message: "Test message 4"}
    ]
  }
];

posts = new PostsCollection;
posts.reset(blogData);

console.log(posts.get(1).comments.pluck("message"));