Serg
Serg

Reputation: 45

Have got some problems with sorting and rendering data with backbone.js

Have got some problems with sorting and rendering data with backbone.js There is sorting by 'title' in comparator. This.model.collection has models after sorting by title, but when rendering starts models views after sorting by order.

    var TodoList = Backbone.Collection.extend({

    model: Todo,

    comparator: function(todo) {
        return todo.get('title');
    },

//function for sorting
    sortByDate: function () {
       this.comparator = function(todo){
           return todo.get('title');
       };
       this.sort();
    }

    });

    var TodoView = Backbone.View.extend({

    tagName:  "li",

    template: _.template($('#item-template').html()),

    initialize: function() {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
    },

    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
    });

Upvotes: 0

Views: 77

Answers (1)

Jack
Jack

Reputation: 11003

Providing a comparator for a collection just ensures that it's models are maintained in a sorted order, if you want to render it in that order you just need to retrieve the models from the collection (most commonly this is done in your collection view) and render them.

For example in your case since you don't have a collection view you can do the following

todoList.each(function (todo) {
  $('#output').append(new TodoView({model: todo}).el);
});

Generally though, you would have this code as part of your collection view. You might also want to maintain a reference to your views so you can easily re-render or remove them. for example

var TodoCollectionView = Backbone.View.extend({

    views: {}, 

    render: function () {
        var frag = document.createDocumentFragment();
        this.collection.each(function (model) {
           var view = this.viewForModel(model);
           frag.appendChild(view.render().el);
        },this);

       this.$el.html(frag);
    },

    viewForModel: function (model) {
        var view;    
        if (this.views[model.cid]) {
           view = this.views[model.cid];
        } else {
           view = new TodoView({model: model});
           this.views[model.cid] = view;
        }
       return view;
    }
});

Here's a link to a jsbin

Upvotes: 1

Related Questions