Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pluck a Backbone collection's attribute

I want to create an array of specific attribute values from a Backbone collection.

var days = _.select(
    this.collection.models,
    function(model) {
        return model.attributes.type === 'session';
    }
);

days = _.pluck(days, 'attributes'),
days = _.pluck(days, 'date');

This works, but seems inefficient. Is there a way to accomplish the same thing without having to define days three times?

like image 720
Philip Schweiger Avatar asked Sep 28 '11 17:09

Philip Schweiger


People also ask

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

What is collections in Backbone JS?

Advertisements. Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.


1 Answers

pluck is a convenience method that wraps map, and map is available directly on the collection, which should make this easier.

assuming you are trying to get the date attribute out of your models, you can do this:

days = this.collection.map(function(model){
  return model.get('date');
});

your select call is also available on the collection directly, as the filter method.

days = this.collection.filter(function(model){ 
  return model.attributes.type === 'session'; 
});

you can chain these two together, but it helps if you define methods separately:

var sessionFilter = function(model){
  return model.attributes.type === 'session'; 
};
var getDate = function(model){ return model.get('date'); }

days = this.collection.filter(sessionFilter).map(getDate);

this should return the results your looking for... or something close to this at least :)

like image 65
Derick Bailey Avatar answered Oct 29 '22 19:10

Derick Bailey