我正在使用Backbone构建一个留言板,并在collection.fetch()中发送两个数组(帖子和用户)。使用.parse,我可以将帖子数组拉出以在列表视图中呈现这些帖子,但我希望将用户数组传递到视图中,以运行一个循环,在该循环中,我可以根据用户id匹配用户和帖子。
Posts_Controller (Rails)
def index
@users = User.all
@posts = Post.all
compiled = {users: @users, posts: @posts}
respond_to do |format|
format.json {render :json => compiled.to_json}
format.html
end
end
PostCollection (Backbone)
MessageBoard.Collections.PostCollection = Backbone.Collection.extend({
model: MessageBoard.Models.Post,
url: '/posts',
parse: function(data) {
var posts = data.posts;
return posts;
}
});
MessageBoard.js
MessageBoard.initialize = function() {
var postCollection = new MessageBoard.Collections.PostCollection();
var postListView = new MessageBoard.Views.PostListView({
collection: postCollection,
el: $('.posts')
});
postCollection.fetch();
}
$(document).ready(function(){
MessageBoard.initialize();
});任何想法都将不胜感激。谢谢!
发布于 2014-08-07 03:55:40
您可能需要考虑的一件事是在顶层保留一个用户集合和一个帖子集合,并且在解析帖子集合时还可以设置用户集合。然后,在视图中,从用户集合中获取带有帖子作者id的用户。
// assuming
MessageBoard.users = new MessageBoard.Collections.Users();
// you might do something like this
MessageBoard.Collections.PostCollection = Backbone.Collection.extend({
model: MessageBoard.Models.Post,
url: '/posts',
setupUsers: function (usersData) {
MessageBoard.users.set(usersData, { parse: true });
},
parse: function (data) {
var posts = data.posts;
if(data.users) {
this.setupUsers(data.users);
}
return posts;
}
});
// maybe in your Post model
MessageBoard.Models.Post = Backbone.Model.extend({
// TODO: memoize
author: function () {
return MessageBoard.users.get(this.get('author_id'));
}
});https://stackoverflow.com/questions/25162002
复制相似问题