Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save CoralineAda/5073375 to your computer and use it in GitHub Desktop.
Save CoralineAda/5073375 to your computer and use it in GitHub Desktop.
Sort Backbone collection by key with direction. Works with both numeric and alphabetical values.
MyApp.FooCollection = Backbone.Collection.extend(
model: MyApp.Foo,
sort_key: 'points',
sort_direction: 'desc'
comparator: (a, b) ->
key_1 = a.get(@sort_key)
key_2 = b.get(@sort_key)
if Number(key_1) == parseInt(key_1)
key_1 = parseInt(key_1)
key_2 = parseInt(key_2)
if @sort_direction == 'desc'
return -1 if key_1 > key_2
return 1 if key_1 < key_2
return 0
else
return 1 if key_1 > key_2
return -1 if key_1 < key_2
return 0
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment