BackBone Js不会删除/更新服务器的模型

时间:2014-10-17 12:04:00

标签: javascript jquery backbone.js asp.net-web-api

我有一个应用程序读取/创建/更新模型并将其保存到服务器。但是现在我能够从数据库中读取并保存模型。但我无法从服务器删除/更新模型。目前,视图会被删除模型,但不会删除模型 这是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();
    }
});

的MainView

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;

});

1 个答案:

答案 0 :(得分:0)

现在,您在URL上定义了Backbone.Collection,但Backbone.Model上没有定义,这意味着您必须通过Collection完成所有AJAX工作。它不一定是这样的:您可以在服务器端为Model AJAX操作添加第二个URL,或者两者甚至可以共享一个URL(如果你适当地设置它)。

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

  1. 服务器上可以使用DELETE方法处理请求的URL(与通常的GET或POST方法相比)
  2. url上设置为该服务器端网址的Backbone.Model媒体资源
  3. 一旦你有this.destroy();的呼叫将创建DELETE AJAX请求,你的服务器将收到该请求并知道它应该删除相应的数据库记录,然后该模型将在客户端上被删除 - 和服务器端。