BackBoneJs不会将模型删除/更新到服务器

BackBoneJs donot Delete/Update Model to the server

本文关键字:更新 服务器 删除 模型 BackBoneJs      更新时间:2023-09-26

我有一个应用程序,它读取/创建/更新模型并将其保存到服务器。但现在我可以从数据库中读取模型并将其保存到数据库中。但我无法从服务器中删除/更新模型。当前,视图会被删除,但不会删除模型本身这是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用于ModelAJAX操作,或者两者甚至可以共享一个URL(如果设置得当)。

如果您希望能够调用this.destroy();并将其反映在服务器上,那么重要的部分是您需要:

  1. 服务器上的URL,可以使用DELETE方法(与通常的GET或POST方法相比)处理请求
  2. Backbone.Model上设置为该服务器端URL的url属性

一旦你知道你对this.destroy();的调用将创建一个DELETE AJAX请求,你的服务器将收到该请求,并知道它应该删除适当的数据库记录,然后该模型将在客户端和服务器端被删除。