testing a handful of the underscore methods on collections

This commit is contained in:
Jeremy Ashkenas
2010-10-06 13:52:25 -04:00
parent 655ab7fa1c
commit d343aa5fec
2 changed files with 28 additions and 4 deletions

View File

@@ -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'];

View File

@@ -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);
});
});