Adds pluckMultiple function to Backbone.js collection
pluckMultiple allows you to pass in an array of attribute names as a "schema" and it will return an array of objects derived from the models of the array based on the "schema"
by Spencer Wasden
July 01, 2015
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
JavaScript
_.extend(Backbone.Collection.prototype, {
pluckMultiple : function (attrs) {
var plucked = this.map(function(model) {
return _.pick(model.toJSON(), attrs);
});
return plucked;
}
});
var c = new Backbone.Collection([
{id:1, name:"raju", age:23, sex: 'male', title: 'manager'},
{id:2, name:"ramesh", age:54, sex: 'male', title: 'tech'}
]);
var plucked = c.pluckMultiple(['name','title']);
console.log( c.pluckMultiple(['name','title']) );
var b = $('body');
_.each(plucked, function(p){
b.append(p.name + '.........' + p.title);
b.append('<br/>');
});