documentcloud/backbone — pull request #1962 by caseywebdev (2012-12-17 23:22:56+00:00)
Title: Trigger `sort` after `add`s for efficient reordering

So now that we have the handy `sort` event, we need to put it to good use! Here's the situation:

```js
initialize: function () {
this.modelViews = {};
this.listenTo(this.collection, 'add', this.addModel);
this.listenTo(this.collection, 'sort', this.sort);
},

addModel: function (model) {
var view = (new ModelView({model: model})).render();
this.modelViews[model.cid] = view;
this.$el.append(view.el);
},

sort: function () {
for (var i = 0; l = this.collection.length; i < l; ++i) {
this.$el.append(this.modelViews[this.collection.models[i].cid].el);
}
}
```

Now I'm set to `add` models to my collection and

1. Ensure they are added to the DOM
2. Stay in the correct order without worrying about wasted re-sorts

An example of (2)...

```js
collection.add(modelInCollection); // will not trigger sort
collection.add(modelInCollection, {merge: true}); // will trigger sort
```

Without this patch, the only way `sort` gets used is if `sort` is manually called...and that's not living to it's potential.