你能在Backbone中串起方法吗?

时间:2012-07-04 00:30:21

标签: ruby-on-rails backbone.js coffeescript

假设我想要wherepluck我的应用之鸟。

首先,我想找到所有名词的word_type

然后我想采摘word属性,以便最终结果是:

所有的名词都是。

["Lion", "Capybara", "Cat"]

当我尝试:

@words = new Project.Collections.WordsCollection()
@words.where(word_type: "noun").pluck("word_type")

它返回:

this.words.where({word_type: "noun"}).pluck is not a function

1 个答案:

答案 0 :(得分:3)

问题是where返回一个模型数组,并且该数组没有混入任何Underscore方法。您可以展开pluck(实际上只是特定类型的map):

_(@words.where(work_type: 'noun')).map (m) -> m.attributes.word_type

或使用Underscore mixins

@chain()
    .filter((m) -> m.attributes.word_type == 'noun')
    .map((m) -> m.attributes.word_type)
    .value()

或者,既然您正在过滤和采集同样的东西,那么您可以在以下情况下计算匹配并构建数组:

n = @reduce(
    ((n, m) -> n += (if m.attributes.word_type == 'noun' then 1 else 0)),
    0
)
matches = ('noun' for i in [0 ... n])