From 1d90bb9cfc304e24b3c8ea67b0c770388a1e9bf2 Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Thu, 12 Jan 2012 15:13:22 -0500 Subject: [PATCH] binding the comparator function before using it, so that you can rely on properties of your collection within it. --- backbone.js | 5 +++-- test/collection.js | 12 ++++++++++++ test/model.js | 1 - 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/backbone.js b/backbone.js index f72eb2fb..beadedcc 100644 --- a/backbone.js +++ b/backbone.js @@ -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; diff --git a/test/collection.js b/test/collection.js index eecddb8e..e6befb5b 100644 --- a/test/collection.js +++ b/test/collection.js @@ -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'); }); diff --git a/test/model.js b/test/model.js index d93122a2..2e049e90 100644 --- a/test/model.js +++ b/test/model.js @@ -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; }});