Backbone comparator
http://stackoverflow.com/questions/12005162/backbone-js-comparator-function-isnt-working-properly/12005350#12005350
by Julian Garcia Castillo
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>
JavaScript
var MyModel = Backbone.Model.extend({});
var MyCollection = Backbone.Collection.extend({
model: MyModel,
comparator: function( a, b ) {
var time_a = a.get('created_at_time');
var time_b = b.get('created_at_time');
if(time_a < time_b) return -1;
else if(time_a > time_b) return 1;
else return 0; // time_a === time_b
}
});
var myCollection = new MyCollection();
myCollection.add({ "created_at_time": "1" } );
myCollection.add({ "created_at_time": "2" } );
myCollection.add({ "created_at_time": "4" } );
myCollection.add({ "created_at_time": "3" } );
myCollection.each( function( model ) {
console.log( model.get( "created_at_time" ) );
});