2

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

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

编辑: Prepend 方法似乎有效,但我也尝试过这样的比较器,它似乎不起作用,我的问题是什么?

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

1 回答 1

5
  1. 使用prepend方法代替append
  2. 使用比较器以您想要的顺序存储模型。

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


我建议阅读这篇很棒的文章 -使用 DocumentFragment 渲染主干集合

于 2013-06-10T19:35:49.547 回答