[Pkg-javascript-commits] [backbone] 173/281: binding the comparator function before using it, so that you can rely on properties of your collection within it.

Jonas Smedegaard js at moszumanska.debian.org
Sat May 3 17:02:09 UTC 2014


This is an automated email from the git hooks/post-receive script.

js pushed a commit to tag 0.9.0
in repository backbone.

commit 1d90bb9cfc304e24b3c8ea67b0c770388a1e9bf2
Author: Jeremy Ashkenas <jashkenas at gmail.com>
Date:   Thu Jan 12 15:13:22 2012 -0500

    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 f72eb2f..beadedc 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 eecddb8..e6befb5 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 d93122a..2e049e9 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;
     }});
 

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/backbone.git



More information about the Pkg-javascript-commits mailing list