Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <a href="http://backbonejs.org/#Collection-comparator"><code>comparator</code></a> function is used to compare two models in the collection and it can compare them in any (consistent) way that it wants to. In particular, it can choose which model attribute to use so you could have something like this in your collection:</p> <pre><code>initialize: function() { this.sort_key = 'id'; }, comparator: function(a, b) { // Assuming that the sort_key values can be compared with '&gt;' and '&lt;', // modifying this to account for extra processing on the sort_key model // attributes is fairly straight forward. a = a.get(this.sort_key); b = b.get(this.sort_key); return a &gt; b ? 1 : a &lt; b ? -1 : 0; } </code></pre> <p>and then you just need some methods on the collection to change the <code>sort_key</code> and call <a href="http://backbonejs.org/#Collection-sort"><code>sort</code></a>:</p> <pre><code>sort_by_thing: function() { this.sort_key = 'thing'; this.sort(); } </code></pre> <p>In older Backbones, calling <code>sort</code> will trigger a <code>"reset"</code> event whereas newer versions will trigger a <code>"sort"</code> event. To cover both cases you can listen to both events and re-render:</p> <pre><code>// in the view... initialize: function() { this.collection.on('reset sort', this.render, this); } </code></pre> <p>Demo: <a href="http://jsfiddle.net/ambiguous/7y9CC/">http://jsfiddle.net/ambiguous/7y9CC/</a></p> <p>You can also use <a href="http://backbonejs.org/#Events-listenTo"><code>listenTo</code></a> instead of <a href="http://backbonejs.org/#Events-on"><code>on</code></a> to help you avoid zombies:</p> <pre><code>initialize: function() { this.listenTo(this.collection, 'reset sort', this.render); } </code></pre> <p>Demo: <a href="http://jsfiddle.net/ambiguous/nG6EJ/">http://jsfiddle.net/ambiguous/nG6EJ/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload