骨干删除模型
问题描述:
在这种情况下,它不会触发Http方法删除萤火虫当我点击清除,即使元素从DOM中删除。骨干删除模型
var DecisionItemView = Backbone.View.extend({
tagName: "li",
template: _.template($('#item-template').html()),
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
},
events:{
"click span.decision-destroy": "clear"
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
clear: function() {
var answer = confirm("Are you sure you want to delete this decision?");
if (answer) {
this.model.destroy({
success: function() {
console.log("delete was a success");
}
});
}
},
remove: function(){
$(this.el).remove();
}
});
答
您的模型是否有ID?否则,destroy方法不会触发一个http请求。
一些代码来检查这个
var M=Backbone.Model.extend({
url:'/echo/json/'
});
var DecisionItemView = Backbone.View.extend({
tagName: "li",
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
},
events:{
"click span.decision-destroy": "clear"
},
render: function() {
var txt=(this.model.get("id")) ? "Clear with id":"Clear without id";
$(this.el).html("<span class='decision-destroy'>"+txt+"</span>");
return this;
},
clear: function() {
var answer = confirm("Are you sure you want to delete this decision?");
if (answer) {
this.model.destroy({
success: function() {
console.log("delete was a success");
}
});
}
},
remove: function(){
$(this.el).remove();
}
});
var m1=new M({id:1}); var m2=new M();
var view1=new DecisionItemView({model:m1});
$("ul").append(view1.render().$el);
var view2=new DecisionItemView({model:m2});
$("ul").append(view2.render().$el);
感谢您指出,如果模型没有一个id属性,该HTTP删除方法不会被调用。我实际上需要销毁一个模型而不进行HTTP Delete调用。为了实现这一点,我只需在销毁模型之前执行'this.unset(“id”);''。我发现Backbone文档中没有提到这种行为,所以再次感谢。 – 2012-07-26 22:46:19