如何采摘从骨干网收集多个属性? [英] How to pluck multiple attributes from a Backbone collection?
问题描述
我想从骨干集合采摘多个属性,但它返回未定义
。
I am trying to pluck multiple attributes from a Backbone collection but it returns undefined
.
集
{
id:1,
name:"raju",
age:23,
sex:male,
hobbies:..
}
{
id:2,
name:"ramesh",
age:43,
sex:male,
hobbies:..
}
... //many models
我试图从集合获取多个属性。
I am trying to get multiple attributes from collection.
collection.pluck(["id","name","age","sex"]);
期望的输出
[{//multiple attributes},{}]
有任何替代方式来获得多个属性?
is there any alternative way to get multiple attributes?
推荐答案
由于@elclanrs说, collection.pluck 提取一个属性,你将不得不使用 _.map 用自定义提取功能。类似
As @elclanrs said, collection.pluck extracts a single attribute, you will have to use _.map with a custom extraction function. Something like
var c = new Backbone.Collection([
{id: 1, name: "raju", age: 23, sex: "male"},
{id: 2, name: "ramesh", age: 43, sex: "male"}
]);
var plucked = c.map(function (model) {
return _.pick(model.toJSON(), ["name", "age"]);
});
console.log(plucked);
和演示 http://jsfiddle.net/U7p9u/
您可以通过合并 Collection.invoke $ C $简化这个调用C>
和 Model.pick
You could simplify this call by combining Collection.invoke
and Model.pick
var c = new Backbone.Collection([
{id: 1, name: "raju", age: 23, sex: "male"},
{id: 2, name: "ramesh", age: 43, sex: "male"}
]);
plucked = c.invoke("pick", ["name", "age"]);
console.log(plucked);
在一个类似的精神,只要您提取功能是在原型的模型定义的:
In a similar spirit, if your extraction function is defined on the prototype of your models:
var M = Backbone.Model.extend({
mypluck: function () {
return this.pick("name", "age");
}
});
var C = Backbone.Collection.extend({
model: M
});
var c = new C([
{id: 1, name: "raju", age: 23, sex: "male"},
{id: 2, name: "ramesh", age: 43, sex: "male"}
]);
var plucked = c.invoke("mypluck");
console.log(plucked);
这篇关于如何采摘从骨干网收集多个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!