Skip to content

Commit

Permalink
binding the comparator function before using it, so that you can rely…
Browse files Browse the repository at this point in the history
… on properties of your collection within it.
  • Loading branch information
jashkenas committed Jan 12, 2012
1 parent a8dbe4e commit 1d90bb9
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
5 changes: 3 additions & 2 deletions backbone.js
Expand Up @@ -481,10 +481,11 @@
sort : function(options) {
options || (options = {});
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
var boundComparator = _.bind(this.comparator, this);
if (this.comparator.length == 1) {
this.models = this.sortBy(this.comparator);
this.models = this.sortBy(boundComparator);
} else {
this.models.sort(this.comparator);
this.models.sort(boundComparator);
}
if (!options.silent) this.trigger('reset', this, options);
return this;
Expand Down
12 changes: 12 additions & 0 deletions test/collection.js
Expand Up @@ -217,6 +217,18 @@ $(document).ready(function() {
equals(col.indexOf(tom), 2);
});

test("Collection: comparator that depends on `this`", function() {
var col = new Backbone.Collection;
col.negative = function(num) {
return -num;
};
col.comparator = function(a) {
return this.negative(a.id);
};
col.add([{id: 1}, {id: 2}, {id: 3}]);
equals(col.pluck('id').join(' '), '3 2 1');
});

test("Collection: remove", function() {
var removed = otherRemoved = null;
col.bind('remove', function(model){ removed = model.get('label'); });
Expand Down
1 change: 0 additions & 1 deletion test/model.js
Expand Up @@ -318,7 +318,6 @@ $(document).ready(function() {
options.success.call(this, {admin: true});
};
model.save(null, {error: function(model, error) {
console.log('erroring!');
lastError = error;
}});

Expand Down

0 comments on commit 1d90bb9

Please sign in to comment.