Permalink
Browse files

Add pluck method that takes an attribute name and returns an array of…

… values.
  • Loading branch information...
benpickles committed Jul 13, 2010
1 parent 07f790c commit 3d1946d374d15d8dc8ae6bb85dc1c676c4ad32a2
Showing with 26 additions and 0 deletions.
  1. +1 −0 CHANGELOG.markdown
  2. +11 −0 src/model_class_methods.js
  3. +14 −0 test/public/tests/model_class_methods.js
View
@@ -1,5 +1,6 @@
# Changelog
+* Add `pluck` method that takes an attribute name and returns an array of values.
* Fix for callbacks being wrongly called on multiple instances - they were being stored on the prototype and thus being shared across instances. Thanks to Oliver Nightingale for identifying the bug and writing a test case.
## 0.8.4
View
@@ -60,6 +60,17 @@ Model.ClassMethods = {
return all[all.length - 1] || null;
},
+ pluck: function(attribute) {
+ var all = this.all()
+ var plucked = []
+
+ for (var i = 0; i < all.length; i++) {
+ plucked.push(all[i].attr(attribute))
+ }
+
+ return plucked
+ },
+
remove: function(id) {
var ids = _.invoke(this.collection, 'id');
var index = _.indexOf(ids, id);
@@ -141,6 +141,20 @@ test("each (and chaining)", function() {
same(titles, ["Bar", "Baz"]);
});
+test(".pluck", function() {
+ var Post = Model('post')
+
+ var post1 = new Post({ id: 1, title: "a" })
+ var post2 = new Post({ id: 2, title: "b" })
+ var post3 = new Post({ id: 3, title: "c" })
+ var post4 = new Post({ id: 4, title: "d" })
+
+ Post.add(post1, post2, post3, post4)
+
+ same(Post.pluck("id"), [1, 2, 3, 4])
+ same(Post.pluck("title"), ["a", "b", "c", "d"])
+})
+
test("sort (and chaining)", function() {
var Post = Model('post');

0 comments on commit 3d1946d

Please sign in to comment.