这是我的集合视图的样子,我如何在集合中安排我的模型,以便最近添加的模型呈现在顶部?
PostsApp.Views.Posts = Backbone.View.extend({
initialize: function(){
this.listenTo(this.collection, 'add', this.addOne);
},
render: function(){
this.collection.forEach(this.addOne, this);
},
addOne: function(post){
var postView = new PostsApp.Views.Post({model:post, collection :this.collection});
postView.render();
this.$el.append(postView.el);
}
});
编辑:前置方法似乎工作但我也尝试过这样的比较器,它似乎没有工作,我的问题是什么?
PostsApp.Models.Post = Backbone.Model.extend({
urlRoot : '/tweet',
idAttribute: '_id',
defaults:{
name: '',
adress: '',
pictureUrl: '',
postListing: '',
comments: '',
date_created: new Date()
}
}
});
PostsApp.Collections.Posts = Backbone.Collection.extend({
model: PostsApp.Models.Post,
url: '/tweet',
comparator: function(post){
return post.get("date_created");
}
});
答案 0 :(得分:5)
prepend
方法代替append
BTW在循环中向DOM添加元素是一个坏主意。
var collection = new (Backbone.Collection.extend({
url : 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=vpetrychuk&count=9',
comparator: function(post) {
// comparator is not necessary because tweets are already sorted
return +new Date(post.get('created_at'));
}
}));
var view = new (Backbone.View.extend({
el : document.body,
collection : collection,
initialize : function () {
this.listenTo(this.collection, 'sync', this.render);
},
render : function () {
var html = []; // or http://davidwalsh.name/documentfragment
this.collection.each(function (model) {
html.unshift('<div>' + model.get('created_at') + '</div>');
});
this.$el.prepend(html.join(''));
}
}));
collection.fetch({dataType:'jsonp'});
http://jsfiddle.net/vpetrychuk/jgztL/
我建议阅读这篇很棒的帖子 - Rendering Backbone Collections with DocumentFragment