javascriptbackbone.jsbackbone-relational

What is the best way to destroy related models when a model is destroyed in backbone relational?


I have complex nested structure of backbone relational models. Every time I destroy a model, it is expected that the all models from relation are destroyed. How do I do it? Apparantely Backbone-Relational does not take care of it.


Solution

  • I would prefer to overload the Backbone model destroy method of your custom models. So you can destroy your nested models. And after that you can destroy the model with Backbone.Model.prototype.destroy.call(this);

    Example:

    var MyModel = Backbone.Model.extend({
      destroy: function(){
        var xhr = this.myNestedModel.destroy();
        xhr.always(_.bind(function(){
           Backbone.Model.prototype.destroy.call(this);
        },this));
        //or if you don't want to wait for the response without always
        //Backbone.Model.prototype.destroy.call(this);
      }
    });