How to override Backbone Collection removal method and then call parent

I follow the guidelines from posts in SO and elsewhere, but can't get this to work.

I want to override the delete function in all Backbone collections to trigger the delete event after deleting all models.

I tried this: fiddle here

Backbone.Collection.prototype.remove = function(models, options){
    console.log('removing');
    Backbone.Collection.prototype.remove.call(this, models, options);
    this.trigger('removed', models);    
};

var MyColl = Backbone.Collection.extend({ });
var MyModel = Backbone.Model.extend({ });

var myColl = new MyColl();
var myModel = new MyModel();

myColl.add(myModel);
myColl.remove(myModel);

... but it seems to call itself recursively and never runs the parent (base) delete method.

How can I override the delete method correctly and call the base method?

+3
source share
4 answers

Underscore wrap(), , Underscore Backbone. wrap(), , :

Backbone.Collection.prototype.remove = _.wrap(
    Backbone.Collection.prototype.remove,
    function(original_remove, models, options) {
        // Capture original function arguments
        var original_args = Array.prototype.splice.call(arguments, 0, 1);

        // Before
        console.log('removing');

        // Call original function with original arguments
        original_remove.apply(this, original_args);

        // After
        this.trigger('removed', models);
    });

- Array.prototype.splice, ( Underscore ). apply() , , call(), , .

Array.prototype.splice, arguments.splice(), , arguments Javascript Array .

+2

remove, remove Backbones Collection, .

:

var MyCollection = Backbone.Collection.extend({
  remove: function(models, options) {
    // Do your stuff
    // ..

    // Call the parent
    Backbone.Collection.prototype.remove.call(this, models, options)
  }
});

MyCollection Backbone.Collection, .

+3

Rewriting the prototype, so when you call it, it will continue recursing. You need to either create a new base collection that will be expanded, or add functionality to an existing extension - depending on how you can reuse it.

var MyBaseCollection = Backbone.Collection.extend({
    remove: function(models, options){
        console.log('removing');
        Backbone.Collection.prototype.remove.call(this, models, options);
        this.trigger('removed', models);    
    }
});

var MyColl = MyBaseCollection.extend({ });

or add it to MyColl directly.

0
source

You do it like this:

var remove = Backbone.Collection.prototype.remove;
Backbone.Collection.prototype.remove = function(models, options){
    console.log('removing');
    remove.call(this, models, options);
    this.trigger('removed', models);    
};

Here is an example

0
source

All Articles