简体   繁体   English

按属性排序Backbone.js

[英]Sort by attributes Backbone.js

I am trying to sort a collection and then update the view with the sorted collection. 我正在尝试对集合进行排序,然后使用已排序的集合更新视图。 What I am trying is to sort a todo list by done or not done tasks. 我正在尝试按已完成或未完成的任务对待办事项列表进行排序。 In my collection view I have this method: 在我的集合视图中,我有以下方法:

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

My problem is that I don't know how to ask the view to render with the value returned by the sort_done method, and I also don't want to lose any information contained in the original collection. 我的问题是,我不知道如何请求使用sort_done方法返回的值来呈现视图,而且我也不想丢失原始集合中包含的任何信息。

One way would be to set a comparator on the collection, and then re-render your view on the collection's 'sort' event. 一种方法是在集合上设置一个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();
}

One disadvantage with this approach is that if the collection is shared between views, this will affect all views of the collection. 这种方法的一个缺点是,如果集合在视图之间共享,那么这将影响集合的所有视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM