问题
I have this model -
class pt.SearchResultModel extends Backbone.Model
defaults:
id:"",
image:"",
colour:""
I am trying this -
_.pluck(resultsCollection,'id')
But it keeps returning undefined - not sure what's going on.
What syntax error am I making?
回答1:
The Underscore array methods are embedded (so to speak) into Backbone collections. You can call them directly on them:
resultsCollection.pluck 'id'
In most of the cases you could also use the Underscore methods over the collection's models
attribute (which is a plain-old array), like _.pluck someCollection.models, 'someAttr'
, but notice that the case of pluck
is special, as Backbone models will usually not have their attributes as own properties (you have to call get to access them). The implementation of Backbone's pluck
is very straightforward nevertheless :)
回答2:
As others mentioned you can use the pluck method of your collection directly which delegates to underscore's pluck method.
However I noticed that if for example you filter your collection you will end up with a plain array of models and as such don't have the collection's pluck
method. In this case what you can do is first pluck the attributes
attribute and then pluck the id
for example something like this should work
_.pluck(_.pluck(myCollection, 'attributes'), 'id');
Of course you can also just create a new collection and pass in these models and then have access to the collections pluck
method.
回答3:
It should be:
resultsCollection.pluck('id');
Underscore methods on Backbone collections are used in this way and not in their original form _.method()
回答4:
Backbone.Collection
automatically provides a good part of underscore.js
functions. So you can write resultsCollection.pluck('id')
, which is a bit better.
Now, about your question : pluck
uses 'get' internally to retrieve your attributes. This, plus your result means that your model does not have id
defined as an attribute.
回答5:
When you are calling _.pluck(resultsCollection,'id')
, you call the pluck method on the collection object.
This collection has a models attribute, but no id attribute.
That's why it's much more better to call resultsCollection.pluck('id')
wich will do all the work for you :
- go to models attribute
- go to each attributes attribute of each model
- find the wanted id value and put it into the result array
来源:https://stackoverflow.com/questions/12402146/pluck-of-backbone-collection-not-working