sorting - How to sort and filter backbone collection -
relatively new backbone. i'm trying filter , sort collection before passing off template. can sort or filter, can't figure out how both. tried chaining them, creating variable hold filter sort on that, can't work. advice?? thanks!
# can filter this: mon = @collection.where({ target: '#day-mon' }) # can sort 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')
your problem where , sortby homecoming arrays — not collections — , arrays don't have where or sortby methods. where or sortby, lose access backbone collection , underscore utilities.
you can of course of study utilize underscore straight on array where gives you:
_(@collection.where(target: '#day-mon')).sortby (t) -> t.get('order') or utilize chain , filter:
@collection.chain().filter((m) -> m.get('target') == '#day-mon').sortby((m) -> m.get('order')).value() where backbone collection method have drop downwards underscore's filter if want chain.
you utilize standard array::sort:
by_order = (a, b) -> [ a, b ] = [ a.get('order'), b.get('order') ] homecoming 1 if(a > b) homecoming -1 if(a < b) homecoming 0 @collection.where(target: '#day-mon').sort(by_order) i find version little easier on eyes if don't utilize anonymous function sort.
demo: http://jsfiddle.net/ambiguous/n6at7/1/
sorting backbone.js collections filter
No comments:
Post a Comment