gpt4 book ai didi

javascript - BackboneJS 未捕获错误 : A "url" property or function must be specified

转载 作者:行者123 更新时间:2023-11-29 19:33:05 25 4
gpt4 key购买 nike

我遇到了这个错误。我能够使用 BackboneJs 预制读取和删除功能,但是当我执行添加方法时出现错误,我们将不胜感激。 JSfiddel 路径是 http://jsfiddle.net/2wjdcgky/

BackboneJS Uncaught Error: A "url" property or function must be specified 

$(function() {

模型

var modelContact = Backbone.Model.extend({
defaults: function() {
return {
Id: 0,
Name: "",
Address: ""
};
},
idAttribute: "Id"
});

模型集合

var contactCollection = Backbone.Collection.extend({
model: modelContact,
url: function() {
return 'api/Contact';
},
add: function(model) {
this.sync("create", model); // Error On create
},
remove: function(model) {
this.sync("delete", model); //Runs Fine
}
});
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() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
clear: function(e) {
contacts.remove(this.model); // runs fine
}
});

主视图

var main = Backbone.View.extend({
el: $("#contactApp"),
events: {
"click #btnsave": "CreateNewContact"
},
initialize: function() {
this.Nameinput = this.$("#contactname");
this.Addressinput = this.$("#contactaddress");

contacts.on("add", this.AddContact, this);
contacts.on("reset", this.AddContacts, this);
contacts.fetch();
},
AddContact: function (contact) {
console.log("AddContact");
var view = new contactView({ model: contact });
this.$("#tblcontact tbody").append(view.render().el);
},
AddContacts: function () {
console.log("AddContacts");
contacts.each(this.AddContact);
},
CreateNewContact: function (e) {
console.log(e);
//Generate an error "BackboneJS Uncaught Error: A "url" property or function must be specified"
contacts.add({ Name: this.Nameinput.val(), Address: this.Addressinput.val() });
}
});
var m = new main;

});

最佳答案

您的 JSFiddle 缺少 Backbone 引用和所有内容。

工作更新:http://jsfiddle.net/apt7hchL/2/

更简单的代码(无需在集合上定义那些addremove 方法!)。还有更常见的 Javascript 编码风格约定。

请注意,我必须手动生成“Id”属性才能创建多个联系人。当您默认设置 Id = 0 时,不会添加第二个相同的模型,因为 Backbone 发现集合中已经有一个 id=0 的模型。

当你想保存时,调用model.save()方法。不要手动调用同步,您通常不需要!

要在添加到集合之前将模型保存到数据库,请使用:

createNewContact: function (e) {
e.preventDefault();
var self = this;
var newContact = new ContactModel({
Name: this.$("#name").val(),
Address: this.$("#address").val()
});
newContact.save({ success: function(model){
self.collection.add(model);
});

//clear form
this.$("#name").val("");
this.$("#address").val("");

关于javascript - BackboneJS 未捕获错误 : A "url" property or function must be specified,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26405278/

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