Charles Peterson
Charles Peterson

Reputation: 71

Backbone remove() from Collection

I have a collection and Im having no luck removing a specific model from it.

The collection is pulled from the server using fetch() which I then populate the view with the data. The collection just contains a list of ids. After the fetch the collection looks like this:

d {**length: 9**, models: Array[9], _byId: Object, _byCid: Object, _ioEvents: Object…}
_byCid: Object
_byId: Object
_callbacks: Object
_ioEvents: Object
addRoom: function () { [native code] }
joinRoom: function () { [native code] }
length: 9
models: Array[9]
0: d
_callbacks: Object
_escapedAttributes: Object
_pending: Object
_previousAttributes: Object
_silent: Object
attributes: Object
**_id: "50c6cf36ece4f5f327000006"**
__proto__: Object
changed: Object
cid: "c3"
collection: d
__proto__: x
1: d
2: d
3: d
4: d
5: d
6: d
7: d
8: d
length: 9
__proto__: Array[0]
removeRoom: function () { [native code] }
__proto__: x

Now when I go to remove a model from the collection I do this

// called from the collection class so this = collection
this.remove({_id:data._id});

And nothing happens, no errors, no nothin. When I log the collection it has the exact same data. Any help would be appreciated.

Upvotes: 3

Views: 7705

Answers (1)

mu is too short
mu is too short

Reputation: 434585

That's not how Collection#remove works. From the fine manual:

remove collection.remove(models, [options])

Remove a model (or an array of models) from the collection.

This is an object:

{_id: data._id}

not a model. Even if you haven't specified a model property for your collection the collection will still contain Backbone.Model instances. So you have to convert your data._id to a model and then hand that model to remove:

var m = collection.where({ _id: data._id})[0];
collection.remove(m);

Ideally you'd create a model "class" for your collection so that you could set the idAttribute:

var M = Backbone.Model.extend({ idAttribute: '_id' });
var C = Backbone.Collection.extend({ model: M });

Then you could use Collection#get to look up the model by _id:

var m = collection.get(data._id);
collection.remove(m);

Upvotes: 7

Related Questions