我有一个集合,我想从中删除一个模型并让它实时同步:
var ClientCollection = Backbone.Firebase.Collection.extend({
model: Client,
url: "https://<my-firebase-url>.firebaseio.com",
autoSync: true
});
我使用我的clear
函数从集合视图中尝试了以下内容:
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中删除模型?
答案 0 :(得分: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;
}});
},
});
<小时/> 上述代码按预期工作