Search code examples
sortingbackbone.js

Backbone cannot sort by/access nested model attribute


I'm not sure why, but I can't sort my collection by a nested attribute in my collection. Below is a screenshot of the collection. I can successfully sort by an attribute like "title" as seen below, but not by a nested attribute like ratings.critics_rating or ratings.audience_score. When I try to log out a or b for the nested attributes, I get "undefined".

This works:

  comparator: (a, b) ->
    log 'comparing'
    a = a.get('title') ## works
    b = b.get('title') ## works
    return 0 if a is b
    if a > b then 1 else -1

This doesn't

  comparator: (a, b) ->
    log 'comparing'
    a = a.get('ratings.critics_rating') ## doesnt work
    b = b.get('ratings.critics_rating') ## doesnt work
    ...

Collection Screenshot


Solution

  • Model.get accesses the attributes on the model but doesn't try to access nested attributes : a.get('ratings.critics_rating') is equivalent to a.attributes['ratings.critics_rating'] and that's not what you want.

    Try a.get('ratings').critics_rating instead,

    comparator: (a, b) ->
        log 'comparing'
        a = a.get('ratings').critics_rating
        b = b.get('ratings').critics_rating
    

    And a demo http://jsfiddle.net/nikoshr/4Lzx1vw5/