Only sort on add when it make sense

This commit is contained in:
Casey Foster
2012-11-30 15:40:01 -08:00
parent d0bed60f84
commit 59850645e6
2 changed files with 19 additions and 3 deletions

View File

@@ -619,7 +619,7 @@
// Add a model, or list of models to the set. Pass **silent** to avoid
// firing the `add` event for every new model.
add: function(models, options) {
var i, args, length, model, existing;
var i, args, length, model, existing, sort;
var at = options && options.at;
models = _.isArray(models) ? models.slice() : [models];
@@ -639,6 +639,7 @@
if (existing || this._byCid[model.cid]) {
if (options && options.merge && existing) {
existing.set(model, options);
sort = true;
}
models.splice(i, 1);
continue;
@@ -651,14 +652,15 @@
if (model.id != null) this._byId[model.id] = model;
}
// Update `length` and splice in new models.
// See if sorting is needed, update `length` and splice in new models.
if (models.length) sort = true;
this.length += models.length;
args = [at != null ? at : this.models.length, 0];
push.apply(args, models);
splice.apply(this.models, args);
// Sort the collection if appropriate.
if (this.comparator && at == null) this.sort({silent: true});
if (sort && this.comparator && at == null) this.sort({silent: true});
if (options && options.silent) return this;

View File

@@ -715,4 +715,18 @@ $(document).ready(function() {
this.ajaxSettings.success([model]);
});
test("`sort` shouldn't always fire on `add`", 1, function() {
var c = new Backbone.Collection([{id: 1},{id: 2},{id: 3}], {
comparator: 'id'
});
c.sort = function() {
ok(1);
return Backbone.Collection.prototype.sort.apply(this, arguments);
}
c.add([]);
c.add({id: 1});
c.add([{id: 2},{id: 3}]);
c.add({id: 4});
});
});