Kavish Dwivedi
Kavish Dwivedi

Reputation: 121

Model getting deleted from view on both success and error of destroy event

Below is a snippet of my code:

var ItemView = Backbone.View.extend({

    initialize: function() {
        _.bindAll(this);
        this.listenTo(this.model,'destroy',this.remove);
    },

    events: {
        "click .cancel-event" : "cancel"
    },

    cancel: function() {
        var confirmationMessage = "Are you sure you want to cancel the item " + this.model.get("title");
        if(window.confirm(confirmationMessage)) {
            this.model.destroy({

                success: function(event, error){
                    //i want to unrender my model from the collection when success happens
                },

                error: function(event, error){
                    //some error handling
                }
            });
        }
    },

Now what's happening is my model is getting removed from the view event if there is a server error. I want to unrender my model from the view only when it is a success destroy.

Upvotes: 0

Views: 107

Answers (1)

Quince
Quince

Reputation: 14990

In the backbone documentation (http://backbonejs.org/docs/backbone.html) they talk about passing an option called wait:true

Destroy this model on the server if it was already persisted. Optimistically removes the model from its collection, if it has one. If wait: true is passed, waits for the server to respond before removal.

so i would try this

 this.model.destroy({
      wait:true,
      success: function(event, error){
        //i want to unrender my model from the collection when success happens
      },

      error: function(event, error){
        //some error handling
      }
  });

Upvotes: 1

Related Questions