如何选择骨干网集合的属性 [英] How to pluck a Backbone collection's attribute

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

问题描述

我想从Backbone集合中创建特定属性值的数组.

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

这有效,但效率低下.有没有一种方法可以完成相同的事情而不必定义days三次?

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

推荐答案

pluck是包装map的便捷方法,并且map可直接在集合中使用,这将使此操作更加容易.

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

假设您尝试从模型中获取date属性,则可以执行以下操作:

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

您的选择调用也可以作为filter方法直接在集合中使用.

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

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

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