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

Gor*_*ven 2 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);
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑:前置方法似乎工作,但我也尝试过这样的比较器,它似乎没有工作,我的问题是什么?

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");
    }
});
Run Code Online (Sandbox Code Playgroud)

Vit*_*huk 5

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

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'});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/vpetrychuk/jgztL/


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