如何采摘从骨干网收集多个属性? [英] How to pluck multiple attributes from a Backbone collection?

查看:121
本文介绍了如何采摘从骨干网收集多个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从骨干集合采摘多个属性,但它返回未定义

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/

您可以通过合并 Col​​lection.invoke 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);

http://jsfiddle.net/U7p9u/5/

在一个类似的精神,只要您提取功能是在原型的模型定义的:

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);

http://jsfiddle.net/U7p9u/3/

这篇关于如何采摘从骨干网收集多个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆