2

I'm looking for a way to, from a backbone collection, retrieve some kind of array of one specific attribute.

var SomeModel = Backbone.Model.extend({
    defaults: function() {
        return {
            attr1: "something",
            attr2: "something",
            attr3: "darkside"
        };
    }
});

var SomeCollection = Backbone.Collection.extend({
    model: SomeModel,
    url: '/data.json',
});

Now assume I have something like above and I only want a collection/array/similar with only the attribute 'attr3'. Is there any nice way to get this (not by manually iterating through the SomeCollection and building a new Collection)? My understanding from underscore function "filter" is that it returns the entire SomeModel based on a certain premise, i.e. this is not what I want. Ideas?

Thanks

4

4 回答 4

4

如果你只想要一个属性,你可以使用_.pluck

SomeCollection.pluck('attr3');

对于多个属性,您可以将集合上的_.map和模型上的_.pick结合起来

SomeCollection.map(function (model) {
    return model.pick('attr2', 'attr3');
});

还有一个演示http://jsfiddle.net/nikoshr/qpyXc/1/

或者,对于更简洁的版本,使用_.invoke

SomeCollection.invoke('pick', 'attr2', 'attr3');

http://jsfiddle.net/nikoshr/qpyXc/3/

于 2013-05-14T14:43:39.683 回答
1

我想你想要 Underscore 的勇气

map 最常见用例的一个方便版本:提取属性值列表。

var attrs = _.pluck(someCollection.models, 'attr3');
于 2013-05-14T14:38:46.183 回答
1

我认为这里有一些误解。在您发布的代码中,您为新创建的模型设置了默认属性。通过以下方式创建的任何模型:

var model = new SomeModel({});

或者:

var collection = new SomeCollection();
// Add to collection
collection.add({});
// Add to collection AND sync with server
collection.create({});

将这些属性设置为给定值,因为您没有在传递给上述函数的哈希中以不同方式定义它们。

相反,我认为您要求的是:

// Create some models
var model_a = new SomeModel({attr1: "Alpha"});
var model_b = new SomeModel({attr1: "Beta"});
var model_c = new SomeModel({attr1: "Gamma"});

// Push them in the collection
var collection = new SomeCollection([model_a, model_b, model_c]);

那么你可以得到一个包含请求模型属性值的字符串数组:

collection.pluck(attributeName);

它本身就是一个继承自 Underscore.js 的函数,Backbone 依赖于它。

我指定这一点是为了明确 _.pluck(array, attributeName)在Backbone 上下文之外也可用,并且适用于arrays,而不是collections。在内部,collection.pluck 调用 _.pluck(collection.models, fieldName)。

于 2013-05-14T14:44:55.257 回答
0
someCollection.pluck.call({
    models: someCollection.where({
        attribute_name:attribute_value
    })
}, attribute_val_to_fetch);
于 2015-04-24T08:02:13.627 回答