簡體   English   中英

按屬性排序Backbone.js

[英]Sort by attributes Backbone.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方法返回的值來呈現視圖,而且我也不想丟失原始集合中包含的任何信息。

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

這種方法的一個缺點是,如果集合在視圖之間共享,那么這將影響集合的所有視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM