Reputation: 479
I am using backbone's collection model to display a sorted list of strings on a backbone view. Here is the model and the comparator:
var MenuItems = Backbone.Collection.extend({
comparator: function (a, b) {
if (a.get('name') < b.get('name')) {
return 1;
} else if (b.get('name') > a.get('name')) {
return -1;
}
},
model: MenuItem,
url: '/items'
});
When the code is run, only the first six of the twelve items in the list are sorted, the rest remains unsorted. When comparator: 'name'
is used the list is fully sorted, but when a function is used, this problem occurs.
Anyone know why this might be happening? Could this be a Backbone bug? I am using Backbone 1.1.0
Upvotes: 1
Views: 62
Reputation: 1553
Here is a working code.
var MenuItems = Backbone.Collection.extend({
comparator: function (a, b) {
if (a.get('name') < b.get('name')) {
return -1;
} else if (a.get('name') > b.get('name')) {
return 1;
}
}
});
Here is jsfiddle with output so you can compare http://jsfiddle.net/ek44Z/2/
The main problem was with function content. You need return -1
in if
statement and compare a
and b
in else if
and return 1
. Basically your else if
have never been called.
Have a good coding.
Upvotes: 4