2
votes

I have an app in backbone and underscore. I have already seen this questions but I haven'0t solved my problem because is a little bit different:
Sorting Backbone Collections
Backbone/Underscore sortBy is not sorting collection

My problem is: I have a collection into a view and I want to sort it by the field order and after print this collection into the template.

I have tried this but doesn't work with underscore:

this.hotels.models = _(this.hotels.models).sortBy("order");
$(this.el).html(this.template({hotels: this.hotels.models}));

How can I sort my collection(model) and after print it inot template? My code doesn't sort my array.

1

1 Answers

7
votes

The models array is an array of Model objects, the attributes of which are stored in model.attributes. Wrapping the array and calling sortBy assumes the objects being sorted are plain objects, and the attribute directly accessible as model.{attribute}.

To get it to do what you want you can pass sortBy a comparator function that gets the attribute you want:

this.hotels.models = _(this.hotels.models).sortBy(function(model) {
    return model.get("order");
});

However this is what Backbone already does in the Collection class. To use the built-in comparator you can simply set the Collection's comparator attribute to the name of the Model attribute by which you want to sort.

Example:

this.hotels.comparator = "order";
this.hotels.sort();
$(this.el).html(this.template({hotels: this.hotels.models}));