Skip to content
This repository has been archived by the owner on Jan 12, 2018. It is now read-only.

Commit

Permalink
Add Collection#sortBy method
Browse files Browse the repository at this point in the history
Sorts the collection by the given attribute of each item.

Collection#sortBy will trigger a 'update' event on the collection, making views update automatically.

Example:

  @collection = new Serenade.Collection([{name:'Jonas'}, {name:'CJ'}])
  @collection.sortBy('name')
  @collection.get(0) # Returns the `{name:'CJ'}` object
  • Loading branch information
cjse committed Mar 18, 2012
1 parent cbbcfa0 commit c044f18
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
12 changes: 12 additions & 0 deletions spec/collection.spec.coffee
Expand Up @@ -42,6 +42,18 @@ describe 'Serenade.Collection', ->
@collection.sort()
expect(@collection).toHaveReceivedEvent('update')

describe '#sortBy', ->
it 'updates the order of the items in the collection', ->
item1 = {name: 'CJ', age: 30}
item2 = {name: 'Anders', age: 37}
@collection.update([item1, item2])

@collection.sortBy('age')
expect(@collection.list).toEqual([item1, item2])

@collection.sortBy('name')
expect(@collection.list).toEqual([item2, item1])

describe '#push', ->
it 'adds an item to the collection', ->
@collection.push('g')
Expand Down
2 changes: 2 additions & 0 deletions src/collection.coffee
Expand Up @@ -28,6 +28,8 @@ class exports.Collection
sort: (fun) ->
@list.sort(fun)
@trigger("update", @list)
sortBy: (attribute) ->
@sort((a, b) -> if a[attribute] < b[attribute] then -1 else 1)
forEach: (fun) ->
forEach(@list, fun)
map: (fun) ->
Expand Down

0 comments on commit c044f18

Please sign in to comment.