BackBoneJs不会将模型删除/更新到服务器
BackBoneJs donot Delete/Update Model to the server
我有一个应用程序,它读取/创建/更新模型并将其保存到服务器。但现在我可以从数据库中读取模型并将其保存到数据库中。但我无法从服务器中删除/更新模型。当前,视图会被删除,但不会删除模型本身这是JSFiddle路径http://jsfiddle.net/u17xwzLh/1/
$(function() {
型号
var modelContact = Backbone.Model.extend({
defaults: function() {
return {
Id: 0,
Name: "",
Address: ""
};
},
//if i add this idAttribute = "Id" it deletes the value from the server
//but i am unable to create a new model/new entry to the database
clear: function () {
// Deletes the model but the changes are not posted back to the server
this.destroy();
}
});
收藏
// runs fine
var contactCollection = Backbone.Collection.extend({
model: modelContact,
url: 'api/Contact'
});
var contacts = new contactCollection;
模型视图
var contactView = Backbone.View.extend({
tagName: "tr",
events: { // runs fine
"click a.destroy": "clear"
},
template: _.template($("#newContacttemplate").html()), // runs fine
initialize: function() {
this.model.on("change", this.render, this);
this.model.on('destroy', this.remove, this);
},
render: function() { // runs fine
this.$el.html(this.template(this.model.toJSON()));
return this;
},
clear: function () {
this.model.clear();
}
});
主视图
var main = Backbone.View.extend({
el: $("#contactApp"),
events: { // runs fine
"click #btnsave": "CreateNewContact"
},
initialize: function() { // runs fine
this.Nameinput = this.$("#contactname");
this.Addressinput = this.$("#contactaddress");
contacts.on("add", this.AddContact, this);
contacts.on("reset", this.AddContacts, this);
contacts.fetch(); // Note : populates all the database values
},
AddContact: function(contact) { // runs fine
var view = new contactView({ model: contact });
this.$("#tblcontact tbody").append(view.render().el);
},
AddContacts: function() { // runs fine
contacts.each(this.AddContact);
},
CreateNewContact: function(e) { // runs fine
contacts.create({ Name: this.Nameinput.val(), Address: this.Addressinput.val() });
}
});
var m = new main;
});
现在您在Backbone.Collection
上定义了URL
,但在Backbone.Model
上没有定义,这意味着您必须通过Collection
完成所有AJAX工作。但不必这样:您可以在服务器端添加第二个URL用于Model
AJAX操作,或者两者甚至可以共享一个URL(如果设置得当)。
如果您希望能够调用this.destroy();
并将其反映在服务器上,那么重要的部分是您需要:
- 服务器上的URL,可以使用DELETE方法(与通常的GET或POST方法相比)处理请求
Backbone.Model
上设置为该服务器端URL的url
属性
一旦你知道你对this.destroy();
的调用将创建一个DELETE AJAX请求,你的服务器将收到该请求,并知道它应该删除适当的数据库记录,然后该模型将在客户端和服务器端被删除。
相关文章:
- Highcharts可以从服务器加载数据,但不能更新
- 服务器发送的事件直到脚本完成才更新
- JQGrid使用服务器编辑后的更新数据刷新数据
- 使用Ajax调用在服务器上实时更新页面
- ASP:代码隐藏的字段变量在从更新面板中的服务器返回时丢失值
- 在从websocket服务器推送消息后更新$scope变量
- 我想听听服务器上的更改,并相应地更新我的网页.我如何用Javascript做到这一点
- 更新网页上Web服务器程序的实时输出
- 多久向服务器发送一次Http请求以检查更新?(Ajax)
- 如何更新服务器's的内容而不重新启动?(node.js)
- 如何在asp中保存服务器中的更新完整日历事件
- 使用Javascript中生成的XML将现有XML保存/更新到服务器
- jQuery侦听器以获取服务器更新
- 使用 XHR 更新服务器文件并将选项添加到 html 选择
- 如何在 asp.net 中更新服务器端执行的 UI 按钮文本
- 使用 AngularJS 更新服务器
- 使用Httppost使用javascript更新服务器上的数据
- 从Sencha应用程序中的表单更新服务器上的xml文件
- 从客户端运行的脚本更新服务器上的javascript变量
- 使用Web开发人员提供的Web API从android应用程序访问/更新服务器中的数据