按属性排序

Sort by attributes Backbone.js

本文关键字:排序 属性      更新时间:2023-09-26

我正在尝试对集合进行排序,然后用排序的集合更新视图。我正在尝试的是按完成或未完成的任务对待办事项列表进行排序。在我的集合视图中,我有这个方法:

    var AddTask = Backbone.View.extend({
    el: '#todos',
    initialize: function(){
        this.collection.fetch();
    },
    events: {
        'click #add': 'addTask',
        'click #filter_done': 'sort_done',
        'keypress #inputTask': 'updateOnEnter'
    },
    addTask: function(){
        var taskTitle = $('#inputTask'). val();
        $('#inputTask').val(""); //clear the input
        if($.trim(taskTitle) === ''){//check if the input has some text in it
            this.displayMessage("Todo's can not be empty");
        }else{
            var task = new Task( {title: taskTitle} ); // create the task model
            this.collection.create(task); //add the model to the collection         
        }
    },
    displayMessage: function(msg){
        $('#inputTask').focus().attr("placeholder", msg);
    },
    updateOnEnter: function(e){
        if(e.keyCode === 13){
            this.addTask();
        }
    },
    sort_done: function(){
        var done = this.collection.where({done: true});
    }
});
var addTask = new AddTask( {collection: tasks} ); 

我的问题是,我不知道如何要求视图呈现由sort_done方法返回的值,我也不想失去原始集合中包含的任何信息。

一种方法是在集合上设置一个comparator,然后在集合的'sort'事件上重新渲染你的视图。

initialize: function() {
    // ...
    this.collection.on('sort', this.render, this);
},
sort_done: function() {
    this.collection.comparator = function(model) {
        return model.get('done') ? 1 : -1;
    };
    // This will trigger a 'sort' event on the collection
    this.collection.sort();
}

这种方法的一个缺点是,如果集合在视图之间共享,这将影响集合的所有视图