最初にアプリが読み込まれるときに、コレクション「リセット」を使用してすべてのデータを入力したいので、最初の AJAX 呼び出しを行ってデータを取得する必要はありません。
Backbone 用に 2 つのモデル、ブログ、およびコメントがあります。ブログにはコメントのリストがあり、これが私の JSON の外観です。
これを Backbone コレクションに正しくロードするにはどうすればよいですか?
最初にアプリが読み込まれるときに、コレクション「リセット」を使用してすべてのデータを入力したいので、最初の AJAX 呼び出しを行ってデータを取得する必要はありません。
Backbone 用に 2 つのモデル、ブログ、およびコメントがあります。ブログにはコメントのリストがあり、これが私の JSON の外観です。
これを Backbone コレクションに正しくロードするにはどうすればよいですか?
バックボーンモデルまたは生のJSONのいずれかをreset
呼び出しに渡すことができます。したがって、これは1つのオプションです。
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/
私はこのようなことをします:
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"));