gpt4 book ai didi

javascript - BackboneJS 未捕获引用错误 : variable is not defined

转载 作者:行者123 更新时间:2023-12-03 11:38:17 24 4
gpt4 key购买 nike

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

所有错误均已解决,这是工作代码

最佳答案

问题来自“渲染”。

确实,您正在设置一个值并删除您的模型:

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

当您“清除”模型时,您必须阻止渲染方法。

关于javascript - BackboneJS 未捕获引用错误 : variable is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26383786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com