2

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

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

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

4

2 回答 2

7

您可以将主干模型或原始 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/

于 2012-12-01T11:01:55.557 回答
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"));
于 2012-12-01T11:27:45.533 回答