Search code examples
backbone.js

Remove last model in Backbone Collection


How do you remove the last model in a Collection?

      if (this.Collection.models.length < newValue) {
        console.log('adding');
        this.Collection.models.add();
      } else {
        console.log('removing');
        // this isnt working, by selecting it by the current collection array index
        // basically this.Collection.remove([this.Collection.models.length-1])
        //this.measuresCollection.models.get('beats').remove(this.measuresCollection.models[i].get('beats')[this.measuresCollection.models[i].get('beats').length]);
      }

I don't know the id, so I would just like to remove the last one.


Solution

  • collection.pop([options])

    Doc: Collection#pop.

    It is below the remove method in the docs. It both removes the last model, and also returns it to you if you need it. If you just want to remove it, don't use the return value.