Skip to content

Commit

Permalink
Add pluck method that takes an attribute name and returns an array of…
Browse files Browse the repository at this point in the history
… values.
  • Loading branch information
benpickles committed Jul 13, 2010
1 parent 07f790c commit 3d1946d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.markdown
@@ -1,5 +1,6 @@
# Changelog # 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. * 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 ## 0.8.4
Expand Down
11 changes: 11 additions & 0 deletions src/model_class_methods.js
Expand Up @@ -60,6 +60,17 @@ Model.ClassMethods = {
return all[all.length - 1] || null; 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) { remove: function(id) {
var ids = _.invoke(this.collection, 'id'); var ids = _.invoke(this.collection, 'id');
var index = _.indexOf(ids, id); var index = _.indexOf(ids, id);
Expand Down
14 changes: 14 additions & 0 deletions test/public/tests/model_class_methods.js
Expand Up @@ -141,6 +141,20 @@ test("each (and chaining)", function() {
same(titles, ["Bar", "Baz"]); 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() { test("sort (and chaining)", function() {
var Post = Model('post'); var Post = Model('post');


Expand Down

0 comments on commit 3d1946d

Please sign in to comment.