title: Update a Backbone Collection property on add/remove/reset
body: <p>I have a Backbone <code>Collection</code>, and I want it to respond in some way to its own updates (i.e. additions, removals, resets). I've run into this in various scenarios, but for the sake of discussion, let's say I'm computing a hash based on model ids, to quickly compare collections:</p>
  
  <pre><code>var HashedCollection = Backbone.Collection.extend({
      updateHash: function() {
          // set a simple hash based on model id
          this.hash = this.pluck('id').sort().join('|');
      } 
  });
  </code></pre>
  
  <p>The question is, <strong>what's the right way to keep my hash up to date?</strong></p>
  
  <p>Possible options:</p>
  
  <ul>
  <li><p>Set a self-listener for events:</p>
  
  <pre><code>this.on('add remove reset', this.updateHash, this);
  </code></pre>
  
  <p>The problem with this is that some actions might be silent, but I still want to update the hash - this is particularly an issue for the first-time set, which can't happen in <code>initialize</code> because the collection doesn't have its models yet, and the initial reset event is silent (<a href="http://documentcloud.github.io/backbone/docs/backbone.html#section-74" rel="nofollow">relevant code</a>). Plus it means that any other component can mess up the collection state just by passing <code>{ silent: true }</code>.</p></li>
  <li><p>Set function overrides for <code>.add</code>, <code>.remove</code>, <code>.reset</code>, and/or <code>.set</code>:</p>
  
  <pre><code>set: function() {
      Backbone.Collection.prototype.set.apply(this, arguments);
      this.updateHash();
  }
  // etc
  </code></pre>
  
  <p>The biggest issue here is handling single <code>add</code>/<code>set</code> calls vs. multiple calls in <code>reset</code> - <code>reset</code> calls <code>add</code> many times, which calls <code>set</code> many times, so wrapping <code>set</code> means we'll update the hash once per item in a reset. If <code>updateHash</code> is more expensive than the simple example above, this can be a real problem. The other, lesser issue is that I end up with a lot of overridden functions, resulting in more semi-boilerplate code and more potential for bugs in core methods.</p></li>
  </ul>
  
  <p>For the sake of discussion, please assume that a) computing the hash is expensive, and b) the hash is referenced frequently.</p>
  
  <p>Is there any better approach here for keeping collection state up to date with its models?</p>