Trip
Trip

Reputation: 27114

Can you string methods in Backbone?

Suppose I'd like to where and pluck my bird of an app.

First I'd like to find all word_types that are nouns.

Then I'd like to pluck the word attribute, so that the final result is :

All words that are nouns.

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

When I try :

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

It returns :

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

Upvotes: 1

Views: 66

Answers (1)

mu is too short
mu is too short

Reputation: 434785

The problem is that where returns an array of models and that array doesn't have any Underscore methods mixed into it. You could unroll the pluck (which is really just specific type of map):

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

or use the Underscore mixins:

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

Or, since you're filtering and plucking the same thing, you count the matches and build your array after:

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

Upvotes: 3

Related Questions