mirror of
https://github.com/jashkenas/backbone.git
synced 2026-01-22 13:28:22 -05:00
binding the comparator function before using it, so that you can rely on properties of your collection within it.
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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'); });
|
||||
|
||||
@@ -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;
|
||||
}});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user