简体   繁体   中英

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.

One way would be to set a comparator on the collection, and then re-render your view on the collection's 'sort' event.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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