0
votes

relatively new to backbone. I'm trying to filter and sort a collection before passing off to the template. I can easily sort OR filter, but I can't figure out how to do both. I tried chaining them, creating a variable to hold the filter then sort on that, but can't get anything to work. Any advice?? Thanks!

# Can filter like this:
monday =  @collection.where({ target: '#day-mon' })

# Can sort like this:
mondaySorted =  @collection.sortBy (t) -> t.get('order')

# Doesn't work:
mondayFilteredSorted = @collection.where({ target: '#day-mon' }).sortBy (t) -> t.get('order')

# Doesn't work:
mondaySorted = monday.sortBy (t) -> t.get('order')
1

1 Answers

0
votes

Your problem is that where and sortBy return arrays — not collections — and arrays don't have where or sortBy methods. As soon as you where or sortBy, you lose access to the Backbone collection and Underscore utilities.

You can of course use Underscore directly on the array that where gives you:

_(@collection.where(target: '#day-mon')).sortBy (t) -> t.get('order')

or you could use chain and filter:

@collection.chain().filter((m) -> m.get('target') == '#day-mon').sortBy((m) -> m.get('order')).value()

where is a Backbone collection method so you have to drop down to Underscore's filter if you want to chain.

You could also use the standard Array::sort:

by_order = (a, b) ->
    [ a, b ] = [ a.get('order'), b.get('order') ]
    return  1 if(a > b)
    return -1 if(a < b)
    return  0
@collection.where(target: '#day-mon').sort(by_order)

I find this version a little easier on the eyes if you don't use an anonymous function with sort.

Demo: http://jsfiddle.net/ambiguous/N6AT7/1/