mirror of
https://github.com/jashkenas/backbone.git
synced 2026-04-30 03:00:06 -04:00
Only sort on add when it make sense
This commit is contained in:
@@ -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;
|
||||
|
||||
|
||||
@@ -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});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user