如何将最新帖子放在骨干上

时间:2013-06-10 19:28:06

标签: backbone.js backbone-views

这是我的集合视图的样子,我如何在集合中安排我的模型,以便最近添加的模型呈现在顶部?

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 个答案:

答案 0 :(得分:5)

  1. 使用prepend方法代替append
  2. 使用comparator进行存储 您的模型按您想要的顺序排列。
  3. 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