0

我有一个集合,我想从中删除一个模型并让它实时同步:

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

我使用我的clear函数从集合 veiw 中尝试了以下内容:

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();
  },
});

但是,这只会从 DOM 中删除模型。

如何从服务器和 DOM 中删除模型?

4

1 回答 1

0

集合视图需要稍微更改才能从 DOM 和服务器中删除。

用于listenTo确保同步更改并将模型从 DOM 中删除。

将以下内容添加到您的initialize函数中。

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

然后在clear函数中使用destroy

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


完整的视图应该是这样的:

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;
    }});
  },
});


上面的代码按预期工作

于 2015-10-05T13:57:42.030 回答