Re: Keep a collection sorted with sortBy

18 views
Skip to first unread message

Jonas Nicklas

unread,
Apr 16, 2013, 3:44:35 PM4/16/13
to seren...@googlegroups.com
There isn't currently any great way of doing this that I know of, unfortunately. There are two options which we've used, one is to use a dependent property, like this:

class Post
  @hasMany "comments"
  @property "sortedComments", get: -> @comments.clone().sortBy("title")

The other is to keep the collection sorted through some kind of attached event, like this:

class Post
  @hasMany "comments"
  constructor: ->
    super
    @comments_property.one =>
      @comments.sortBy("title")
      @comments_property.one(arguments.callee)

The reason we're doing this in such a convoluted way, using `one` instead of just using `bind`, is because calling `sortBy` would usually trigger a change event, so it would inifitely recurse.

It's a bit painful at the moment, so I really want to find a better way.

/Jonas
 


On Tue, Apr 16, 2013 at 6:49 PM, <matteop...@gmail.com> wrote:
I would like to keep a collection sorted using sortBy with a specific  property of the model, for example I would like to make so it is always shown sorted in alphabetical orde based on the title property.


How can I achieve this?

--
You received this message because you are subscribed to the Google Groups "Serenade.js" group.
To unsubscribe from this group and stop receiving emails from it, send an email to serenadejs+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

matteop...@gmail.com

unread,
Apr 17, 2013, 9:17:22 AM4/17/13
to seren...@googlegroups.com
Thanks for the answer, 

I had tried something like the first solution you posted but didn't work probably because I didn't used `clone`. Why it's necessary to use it?

Jonas Nicklas

unread,
Apr 17, 2013, 5:14:00 PM4/17/13
to seren...@googlegroups.com
The reason that `clone` is necessary, is that for some bizarre reason, `sort` is mutative in JavaScript. We kept this behaviour for Serenade Collections, so it's consistent with regular JS.

/Jonas
Reply all
Reply to author
Forward
0 new messages