title: Backbone.js modify newly fetched collection before reset events occur
body: <p>I'm trying to do the following:</p>
  
  <ol>
  <li>Fetch data from the server</li>
  <li>Add a zero-based index to the models before the views are notified</li>
  <li>Finally run have the 'render' events fire for the views</li>
  </ol>
  
  <p>I was trying to do this by using a success callback in the collection</p>
  
  <p><strong>View Before</strong></p>
  
  <pre><code>initialize: () -&gt;
    @collection.on 'reset', @render, this
  
  render: () -&gt; ...render code...
  </code></pre>
  
  <p><strong>Collection Before</strong></p>
  
  <pre><code>search: () -&gt;
    @fetch { 
      success: @fetch_success
    }  
  
  fetch_success: () -&gt;
    for i in [0...collection.models.length]
      collection.models[i].set('go_index', i)
  </code></pre>
  
  <p>Doing things this way was causing the views to fire their render events before the collection was updated by the success callback.  The solution I came up with was to have the views listen to a <code>fetched</code> event, then have the collection fire that after it successfully modifies the collection:</p>
  
  <p><strong>View After</strong></p>
  
  <pre><code>initialize: () -&gt;
    @collection.on 'fetched', @render, this
  
  render: () -&gt; ...render code...
  </code></pre>
  
  <p><strong>Collection After</strong></p>
  
  <pre><code>initialize: () -&gt;
    @on 'reset', @add_index_and_notify, this
  
  add_index_and_notify: () -&gt;
    for i in [0...@models.length]
      @models[i].set('go_index', i)
    @trigger('fetched')
  </code></pre>
  
  <p>This works fine, I'm just wondering if this is the most elegant way to accomplish this or if there is a built-in way that I'm missing.</p>
  
  <p><strong>UPDATE 3/15</strong></p>
  
  <p>I've come up with a cleaner solution that doesn't require the view to do any of the dirty work and I don't have to create a custom event.  The trick is to listen to the <code>sync</code> event (which fires <em>after</em> <code>reset</code>)</p>
  
  <p><strong>View Final</strong></p>
  
  <pre><code>initialize: () -&gt;
    @collection.on 'sync', @render, this
  
  render: () -&gt; ...render code...
  </code></pre>
  
  <p><strong>Collection Final</strong></p>
  
  <pre><code>initialize: () -&gt;
    @on 'reset', @add_index, this
  
  add_index: () -&gt;
    for i in [0...@models.length]
      @models[i].set('go_index', i)
  </code></pre>
  
  <p>Hopefully this pattern can help somebody searching in the future.</p>