Skip to content

Commit

Permalink
Adding Collection#push, pop, shift, and unshift to the API, returning…
Browse files Browse the repository at this point in the history
… references to the model. Fixing a too-unescaped regex.
  • Loading branch information
jashkenas committed Feb 8, 2012
1 parent b86cfeb commit e3ac6f8
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
30 changes: 29 additions & 1 deletion backbone.js
Expand Up @@ -564,6 +564,34 @@
return this;
},

// Add a model to the end of the collection.
push: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, options);
return model;
},

// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},

// Add a model to the beginning of the collection.
unshift: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({at: 0}, options));
return model;
},

// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},

// Get a model from the set by id.
get: function(id) {
if (id == null) return null;
Expand Down Expand Up @@ -819,7 +847,7 @@
};

// Cached regex for cleaning leading hashes and slashes .
var routeStripper = /^[#/]/;
var routeStripper = /^[#\/]/;

// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
Expand Down
12 changes: 9 additions & 3 deletions test/collection.js
Expand Up @@ -57,7 +57,7 @@ $(document).ready(function() {
idAttribute: '_id'
});
var model = new MongoModel({_id: 100});
col.add(model);
col.push(model);
equal(col.get(100), model);
model.set({_id: 101});
equal(col.get(101), model);
Expand Down Expand Up @@ -128,15 +128,15 @@ $(document).ready(function() {
// no id, same cid
var a2 = new Backbone.Model({label: a.label});
a2.cid = a.cid;
col.add(a2);
col.push(a2);
ok(false, "duplicate; expected add to fail");
}, "Can't add the same model to a collection twice");
});

test("Collection: can't add different model with same id to collection twice", function() {
raises(function(){
var col = new Backbone.Collection;
col.add({id: 101});
col.unshift({id: 101});
col.add({id: 101});
ok(false, "duplicate; expected add to fail");
}, "Can't add the same model to a collection twice");
Expand Down Expand Up @@ -228,6 +228,12 @@ $(document).ready(function() {
equal(otherRemoved, null);
});

test("Collection: shift and pop", function() {
var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
equal(col.shift().get('a'), 'a');
equal(col.pop().get('c'), 'c');
});

test("Collection: events are unbound on remove", function() {
var counter = 0;
var dj = new Backbone.Model();
Expand Down

0 comments on commit e3ac6f8

Please sign in to comment.