我是backbonejs的新手我能够添加并显示数据库中的联系人。但我无法使用backbonejs执行删除。 JSFiddle http://jsfiddle.net/L183kw0o/10/ 当我尝试删除它时给我错误
"Uncaught ReferenceError: Id is not defined "
下面是堆栈跟踪 (匿名函数)VM103:2 InjectedScript._evaluateOn VM69:730 InjectedScript._evaluateAndWrap VM69:669 InjectedScript.evaluate VM69:581
这是我的模特
var modelContact = Backbone.Model.extend({
defaults: function () {
return {
Id: 0,
Name: "",
Address: ""
};
},
idAttribute: "Id",
url: function(){
return 'api/Contact/' + this.get("Id");
},
initialize: function () {
if (!this.get("Id")) {
this.set({ "Id": this.defaults().Id });
}
},
clear: function() {
console.log(this.get("Id"));
this.destroy({
error: function(model, response) {
alert("error");
},
success: function(model, response) {
alert("success");
console.log(response);
}
});
}
});
模型集合
var contactCollection = Backbone.Collection.extend({
model: modelContact,
url: function() {
return 'api/Contact';
}
});
var contacts = new contactCollection;
查看
var contactView = Backbone.View.extend({
tagName: "tr",
events: {
"click a.destroy": "clear"
},
template: _.template($("#newContacttemplate").html()),
initialize: function() {
this.model.on("change", this.render, this);
this.model.on('destroy', this.remove, this);
},
render: function () {
if (this.isGoingToBeRemoved) {
return (this);
}
this.$el.html(this.template(this.model.toJSON()));
return this;
},
clear: function (e) {
this.isGoingToBeRemoved = true;
this.model.clear();
}
});
解决了所有错误,这是工作代码
答案 0 :(得分:1)
问题来自“渲染”。
确实,您正在设置一个值并删除模型:
clears: function (e) {
console.log(e);
console.log(this.model);
this.model.set({ // trigger change
Id: 3
});
this.model.get("Id");
this.model.clear(); // remove your model
}
因为JS是异步的,所以你会同时调用“render”和“clear”。当你打电话给this.$el.html(this.template(this.model.toJSON()));
时,model.get('Id')将被删除..所以,你会尝试调用不存在的东西
render: function () {
// console.log(this.model.toJSON());
this.$el.html(this.template(this.model.toJSON())); // this.model.toJSON() == {}
return this;
},
当您“清除”模型时,必须阻止渲染方法。