Search code examples
javascriptbackbone.jsviewdestroy

How do I get rid of model attached to view after using Backbone's model#destroy?


I'm seeing the success callback but in the debugger Chrome Dev Tools, I'm still seeing the model when I type in this.model. I know that it's destroyed on the server side, but can you explain why it's still attached to the view? How do I get rid of it?

        delete: function () {
            this.model.destroy({success: function () {console.log("success in destroy");}});
            debugger;
        }

Solution

  • What you are seeing is correct. Looking at the documentation on model.destroy (or looking to the code) we can see it basically does two things:

    • HTTP DELETEs the server representation of the model
    • Removes the model from any containing collections

    Note that nothing happens to the model itself or to any objects the model may be attached to.

    We can see this behavior with a simple example:

    var foo = new Backbone.Model({foo: 'bar'});
    var foos = new Backbone.Collection([foo]);
    var fooView = new Backbone.View();
    fooView.model = foo;
    
    foo.destroy({success: function () {
        console.log('success');
    }});
    
    console.log(foo, foos, fooView);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone.js"></script>

    Note that nothing happens to foo or fooView.model after executing this code, although foos no longer contains an instance of foo.

    Removing view.model

    If you want to remove the model from the view you can leverage the success callback. Just change your view's delete method (from your question) to something like the following:

    delete: function () {
        this.model.destroy({success: function () {
            delete this.model;
        }.bind(this)});
    }
    

    Alternatively, since we know from the docs that the model will fire a "destroy" event, we can also listen for that event and fire a callback that deletes our model.