gpt4 book ai didi

backbone.js - 如何使用 backbone 将最新的帖子放在首位

转载 作者:行者123 更新时间:2023-12-02 22:00:29 25 4
gpt4 key购买 nike

这是我的 Collection View 的样子,我将如何在集合中排列我的模型,以便最近添加的模型呈现在顶部?

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");
}
});

最佳答案

  1. 使用prepend 方法代替append
  2. 使用comparator储藏您的模型按照您想要的顺序排列。

顺便说一下,在循环中向 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

关于backbone.js - 如何使用 backbone 将最新的帖子放在首位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17031313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com