diff --git a/backbone.js b/backbone.js index 4a863abd..26cc75f0 100644 --- a/backbone.js +++ b/backbone.js @@ -306,6 +306,11 @@ return cid && this._byCid[cid.cid || cid]; }, + // Get the model at the given index. + at: function(index) { + return this.models[index]; + }, + // What are the ids for every model in the set? getIds : function() { return _.keys(this._byId); @@ -316,9 +321,9 @@ return _.keys(this._byCid); }, - // Get the model at the given index. - at: function(index) { - return this.models[index]; + // Pluck an attribute from each model in the collection. + pluck : function(attr) { + return _.map(this.models, function(model){ return model.get(attr); }); }, // Add a model, or list of models to the set. Pass **silent** to avoid @@ -445,7 +450,7 @@ // Underscore methods that we want to implement on the Collection. var methods = ['each', 'map', 'reduce', 'reduceRight', 'detect', 'select', - 'reject', 'all', 'any', 'include', 'invoke', 'pluck', 'max', 'min', 'sortBy', + 'reject', 'all', 'any', 'include', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size', 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty']; diff --git a/test/collection.js b/test/collection.js index 9a026acc..cfd27a66 100644 --- a/test/collection.js +++ b/test/collection.js @@ -44,6 +44,10 @@ $(document).ready(function() { equals(col.at(2), b); }); + test("collections: pluck", function() { + equals(col.pluck('label').join(' '), 'd c b a'); + }); + test("collections: add", function() { var added = null; col.bind('add', function(model){ added = model.get('label'); }); @@ -91,4 +95,19 @@ $(document).ready(function() { equals(model.collection, col); }); + test("collections: Underscore methods", function() { + equals(col.map(function(model){ return model.get('label'); }).join(' '), 'd c b a'); + equals(col.any(function(model){ return model.id === 100; }), false); + equals(col.any(function(model){ return model.id === 1; }), true); + equals(col.indexOf(b), 2); + equals(col.size(), 4); + equals(col.rest().length, 3); + ok(!_.include(col.rest()), a); + ok(!_.include(col.rest()), d); + ok(!col.isEmpty()); + ok(!_.include(col.without(d)), d); + equals(col.max(function(model){ return model.id; }).id, 4); + equals(col.min(function(model){ return model.id; }).id, 1); + }); + });