0

I have a collection from which I would like to delete a model and have it sync in real-time:

var ClientCollection = Backbone.Firebase.Collection.extend({
  model: Client,
  url: "https://<my-firebase-url>.firebaseio.com",
  autoSync: true
});

I have tried the following from the collection veiw using my clear function:

var ClientView = Backbone.View.extend({
  tagName:  "li",
  className: "list-group-item",
  template: _.template("<%= name %>"),
  events: {
    "click .destroy" : "clear"
  },
  initialize: function() {
    this.listenTo(this.model, "change", this.render);
  },
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  },
  clear: function() {
      this.model.remove();
  },
});

However this only removes the model from the DOM.

How do I delete the model from the server AND the DOM?

Michael Doye
  • 8,063
  • 5
  • 40
  • 56

1 Answers1

0

The collection view would need to change slightly for it to be deleted from the DOM and server.

Use listenTo to ensure the changes are synced and have the model removed from the DOM.

Add the following to your initialize function.

// This will listen for the destroy method and then remove the item from the dom
this.listenTo(this.model, "destroy", this.remove);

And then in the clear function use destroy:

clear: function() {
    this.model.destroy({success: function(model, response) {
       // Do something if successful
    }});
},


The full view should be something like this:
var ClientView = Backbone.View.extend({
  tagName:  "li",
  className: "list-group-item",
  template: _.template("<%= name %>"),
  events: {
    "click .destroy" : "clear"
  },
  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.listenTo(this.model, "destroy", this.remove);
  },
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  },
  clear: function() {
    this.model.destroy({success: function(model, response) {
      $('.notification').fadeIn(200).html('Success - Item removed').fadeOut(1000);
      return this;
    }});
  },
});


The above code works as expected
Michael Doye
  • 8,063
  • 5
  • 40
  • 56