Trigger sort after adds for efficient reordering

This commit is contained in:
Casey Foster
2012-12-17 15:11:54 -08:00
parent 25505d6700
commit af7effe1f1
2 changed files with 16 additions and 2 deletions

View File

@@ -662,8 +662,8 @@
push.apply(args, models);
splice.apply(this.models, args);
// Sort the collection if appropriate.
if (needsSort && this.comparator && at == null) this.sort({silent: true});
// Silently sort the collection if appropriate.
if (needsSort &= this.comparator && at == null) this.sort({silent: true});
if (options && options.silent) return this;
@@ -672,6 +672,9 @@
model.trigger('add', model, this, options);
}
// Trigger `sort` if the collection was sorted.
if (needsSort) this.trigger('sort', this, options);
return this;
},

View File

@@ -929,4 +929,15 @@ $(document).ready(function() {
Backbone.ajax = ajax;
});
test("`sort` is trigged on `add` when sorting occurs", 2, function () {
var collection = new (Backbone.Collection.extend({
comparator: 'id'
}))({id: 1, id: 2, id: 3});
collection.on('sort', function () { ok(1); });
collection.add({id: 4}); // trigger
collection.add({id: 1}, {merge: true}); // trigger
collection.add({id: 1}); // don't trigger
collection.add({id: 5}, {silent: true}); // don't trigger
});
});