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

Commit

Permalink
Add Collection#sort method
Browse files Browse the repository at this point in the history
Sorts the collection with the function passed as an argument. Works just like Array#find.

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

Example:

  @collection = new Serenade.Collection([{name:'Jonas'}, {name:'CJ'}])
  @collection.sort((a, b) -> if a.name.length < b.name.length then -1 else 1)
  @collection.get(0) # Returns the `{name:'CJ'}` object
  • Loading branch information
cjse committed Mar 18, 2012
1 parent 89c6018 commit cbbcfa0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
12 changes: 12 additions & 0 deletions spec/collection.spec.coffee
Expand Up @@ -30,6 +30,18 @@ describe 'Serenade.Collection', ->
@collection.update([1,2])
expect(@collection.length).toEqual(2)

describe '#sort', ->
it 'updates the order of the items in the collection', ->
@collection.push('a')
@collection.sort()
expect(@collection.list).toEqual(['a', 'a', 'b', 'c'])
it 'updates the order of the items in the collection', ->
@collection.sort((a, b) -> if a > b then -1 else 1)
expect(@collection.list).toEqual(['c', 'b', 'a'])
it 'triggers an update event', ->
@collection.sort()
expect(@collection).toHaveReceivedEvent('update')

describe '#push', ->
it 'adds an item to the collection', ->
@collection.push('g')
Expand Down
3 changes: 3 additions & 0 deletions src/collection.coffee
Expand Up @@ -25,6 +25,9 @@ class exports.Collection
@_in(element) for element in list
@trigger("update", list)
@trigger("change", @list)
sort: (fun) ->
@list.sort(fun)
@trigger("update", @list)
forEach: (fun) ->
forEach(@list, fun)
map: (fun) ->
Expand Down

0 comments on commit cbbcfa0

Please sign in to comment.