按属性Backbone.js排序

时间:2014-03-10 19:58:24

标签: javascript jquery backbone.js underscore.js

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

    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方法返回的值进行渲染,而且我也不想丢失原始集合中包含的任何信息。< / p>

1 个答案:

答案 0 :(得分:1)

一种方法是在集合上设置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();
}

此方法的一个缺点是,如果集合在视图之间共享,则会影响集合的所有视图。