sunwukung
sunwukung

Reputation: 2815

retrieve element from Backbone.Collection.remove(n)

I'm taking my first steps with Backbone.js, and one of those involves being able to remove an item from a collection, and more importantly, retrieve that item. The Backbone.Collection.remove method simply returns the original collection with the item removed, so at the moment I'm obtaining a reference to the desired item prior to removal:

var Collection = Backbone.Collection.extend(...array of Backbone.Models...),
    removedItem = Collection.get(3);
console.log(Collection.remove(3));//same collection sans #3

My question is if there is a short hand method for retrieving the remove item?

Edit: JFTR, I've read a fair bit of the source, and know that the original method returns a reference to the collection -

remove: function(models, options) {
  // <snip for brevity>
  // chain pattern incoming
  return this;
},

It seemed odd to me that it didn't return the removed item., so I was just wondering if there was another method I'm missing, or a common way of achieving this pattern. Wouldn't be the first time I've used a long workaround when the API had some secret doohickey up it's sleeve...as it is I'll probably extend the class.

Upvotes: 1

Views: 540

Answers (1)

Exploit
Exploit

Reputation: 108

You could add a function to the Backbone.Collection 'type' and use removeModel on every collection you create.

Backbone.Collection.prototype.removeModel(model) {
    var _model = this.get(model);
    this.remove(item);
    return _model;
}

var removedModel = collection.removeModel(model);

Upvotes: 1

Related Questions