使用backbonejs和jquery将模型同步到asp.net服务器

syncing a model to asp.net server using backbonejs and jquery

本文关键字:asp net 服务器 同步 模型 backbonejs jquery 使用      更新时间:2023-09-26

我想看看如何在扩展模型上指定urlRoot时使用model.save()方法保存模型到服务器,但是当我请求model.fetch()do model.save()时,ajax请求永远不会触发。注:如果不使用Collection,我想这是可能的吗?

HTML

<div id="placeholder"></div>
<script type="text/template" id="view_template">
    Hello <%= name %>, here is your script <%= script %>
</script>

模型
 window["model"] = Backbone.Model.extend({
        initialize: function () {
            console.log("CREATED");
        },
        defaults:{
            name:"Please enter your name",
            script:"Hello World"
        },
        urlRoot: "index.aspx",
        validate: function (attrs) {
        },
        sync: function (method, model, success, error) {
            console.log("SYNCING", arguments);
        }
    });
<<h3>视图/h3>
 window["view"] = Backbone.View.extend({
        template:_.template($("#view_template").html()),
        initialize: function () {
            console.log("INITIALISED VIEW");
            this.model.bind("change","render",this);
        },
        render: function (model) {
                console.log("RENDERING");
                $(this.el).append(this.template(model));
                return this;
        }
    });
<<h3>应用程序/h3>
$("document").ready(function () {
    var myModel = new model({
        name: "Stack Overflow",
        script: "alert('Hi SO')"
    });
    var myView = new view({
        model: myModel,
        el: $("#placeholder")
    });
    console.log("SAVING");
    myModel.save();        
    console.log("FETCHING");
    myModel.fetch();

});

你可以在应用程序中看到,我调用save & fetch,但根据文档,这应该触发ajax请求与POST -> SAVE &GET -> FETCH。但它所做的只是在sync函数中将参数记录到控制台。

我认为您没有看到任何Ajax请求的唯一原因是您已经覆盖了模型。同步方法。通常情况下,只有在希望替换Backbone.sync中实现的默认Ajax同步时才会这样做。参见Model中的下面一行。在backbone.js中获取:

return (this.sync || Backbone.sync).call(this, 'read', this, options);

我对你的代码做了一个快速测试,如果我重命名你的模型,我看到Ajax请求。同步方法。