保存方法的意外行为

Unexpected behaviour with save method

以下是我的观点和模型。很明显,每次我为每次调用 initiateTest 准备新的 serverRequestData 数据并将其传递给 save 方法时。

因此,我的服务器调用应该使用 serverRequestData 中的数据进行。它在第一次调用 initiateTest 时正确发生,但从第二次开始我看到前一个服务器调用的响应已通过。

这对我来说真的很奇怪,因为显然我每次都在准备新鲜的 initiateTest

我做错了什么是搞砸了 backbone.js 的一些内部东西?

查看:

define(['jquery', 'underscore', 'backbone', 'models/adhocmodel', 'models/resultmodel',
        'text!templates/adhoc/adhocTemplate.html'], function($, _, Backbone,
        adhocModel, resultModel, adhocTemplate) {

    var adhocHistoryView = Backbone.View.extend({

        resultmod : new resultModel(),
        model : new adhocModel(),
        el : $("#container"),

        events : {
            "click #test" : "initiateTest"
        },

        initiateTest : function() {
            var serverRequestData = {"myid":"AAA",
                       "fname":"Wade",
                       "lname": "Wade",
                       "telephoneNumber":telNum,
                       "testMode":"Initial" };

            console.log(serverRequestData);

            var that = this;
            this.model.save(serverRequestData, {
                url: "forms/serviceDiagnostic/startTest",
                type: "POST",
                contentType: "application/json",
                success : function(model, response) {
                    that.model.adhocCommon.hasTestResultArrived = true;
                    that.model.testResults = response;
                    that.render();
                    $('#container').trigger("create");
                },
                error : function(model, response) {
                    console.log("####### Error recieved ....");
                }
            });
        },

        initialize : function() {
        },

        render : function() {

            console.log(this.model);

            //this.$el.html(adhocTemplate);
            var data = {
                    model:this.model,
                    _:_
            };
            var compiledTemplate = _.template(adhocTemplate, data );

            this.$el.html(null);
            this.$el.html(compiledTemplate);
            return this;
        }
    });

    return adhocHistoryView;
});

型号:

define([ 'backbone' ], function(Backbone) {

    var adhocModel = Backbone.Model.extend({

        initialize : function() {

        },

        poolHandler : null,

        poolCounter : 0,

        adhocCommon : {
            hasTestResultArrived : false
        },

        testResults : {}

    });

    return adhocModel;
});

这就是 Model.save() 的工作原理。 Backbone 希望您的服务器响应服务器中模型的最新状态,并且您的模型将使用该响应进行更新。

另外:

The attributes hash (as in set) should contain the attributes you'd like to change — keys that aren't mentioned won't be altered — but, a complete representation of the resource will be sent to the server (emphasis mine)

因此,在您第一次调用后,模型将根据您的服务器响应进行更新,从下一次开始,它将与您传递给 save() 的属性一起发送。

如果你想改变发送到服务器的内容,你可以覆盖save方法,如果你想改变收到响应时更新到模型中的内容,你可以定义一个parse方法。