diff --git a/backbone.js b/backbone.js index 0bf20516..edca0905 100644 --- a/backbone.js +++ b/backbone.js @@ -734,7 +734,9 @@ // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; - return this._byId[obj.id != null ? obj.id : obj] || this._byCid[obj.cid || obj]; + var idAttr = this.model.prototype.idAttribute; + return this._byId[obj[idAttr] != null ? obj[idAttr] : obj.id != null ? obj.id : obj] + || this._byCid[obj.cid || obj]; }, // Get the model at the given index. @@ -781,7 +783,6 @@ update: function(models, options) { var model, i, l, existing; var add = [], remove = [], modelMap = {}; - var idAttr = this.model.prototype.idAttribute; options = _.extend({add: true, merge: true, remove: true}, options); if (options.parse) models = this.parse(models, options); @@ -794,7 +795,7 @@ // Determine which models to add and merge, and which to remove. for (i = 0, l = models.length; i < l; i++) { model = models[i]; - existing = this.get(model.id || model.cid || model[idAttr]); + existing = this.get(model); if (options.remove && existing) modelMap[existing.cid] = true; if ((options.add && !existing) || (options.merge && existing)) { add.push(model); diff --git a/test/collection.js b/test/collection.js index 4c79e290..9ac954ed 100644 --- a/test/collection.js +++ b/test/collection.js @@ -62,13 +62,15 @@ $(document).ready(function() { strictEqual(collection.last().get('a'), 4); }); - test("get", 3, function() { + test("get", 5, function() { equal(col.get(0), d); equal(col.get(2), b); + equal(col.get({id: 1}), c); + equal(col.get(c.clone()), c); equal(col.get(col.first().cid), col.first()); }); - test("get with non-default ids", 2, function() { + test("get with non-default ids", 4, function() { var col = new Backbone.Collection(); var MongoModel = Backbone.Model.extend({ idAttribute: '_id' @@ -78,6 +80,12 @@ $(document).ready(function() { equal(col.get(100), model); model.set({_id: 101}); equal(col.get(101), model); + + var Col2 = Backbone.Collection.extend({ model: MongoModel }); + col2 = new Col2(); + col2.push(model); + equal(col2.get({_id: 101}), model); + equal(col2.get(model.clone()), model); }); test("update index when id changes", 3, function() {