1

我有一个主干模型,如下所示

define([], function(){
    var instaceUrl;
    var PatientModel = Backbone.Model.extend({
        url: function() {
            return instanceUrl;
        },
        initialize: function(options) {
            instanceUrl = options.instanceUrl;
        },
        defaults: {
            "person": "",
            "identifiers":""
        }
    });
    console.log('Patient model');
    return PatientModel;
});

当我尝试保存患者模型patientModel.save时,请求有效负载中添加了一个额外的instanceUrl属性

var patientModel = new PatientModel({instanceUrl: '/patient'});
...
...
patientModel.set("identifiers", identifiers);
patientModel.set("person", uuid);
patientDetails = patientModel.toJSON();
patientModel.save(patientDetails, {
    beforeSend : sendAuthentication,
    success : function(model, response, options) {
        uuid = response.uuid;
    },
    error : function() {
        alert('failed');
    }
});

模型发送以下有效载荷

{
    "instanceUrl": "/patient", // why is it added ?
    "person": "c014068c-824d-4346-84f0-895eb3ec6af7",
    "identifiers": [
        {
            "preferred": true,
            "location": "f15bc055-765a-4996-a207-ec4945972f33",
            "identifier": "saks9639",
            "identifierType": "866aedab-8a37-4b15-95d3-2b775fc0caac"
        }
    ]
}

REST API 调用成功所需的有效负载是

{
    "person": "c014068c-824d-4346-84f0-895eb3ec6af7",
    "identifiers": [
        {
            "preferred": true,
            "location": "f15bc055-765a-4996-a207-ec4945972f33",
            "identifier": "saks9639",
            "identifierType": "866aedab-8a37-4b15-95d3-2b775fc0caac"
        }
    ]
}

如何避免patientModel考虑instanceUrl作为模型属性?

4

1 回答 1

2

模型构造函数/初始化方法的方法签名是

构造函数/初始化新模型([属性],[选项])

其中传递的第一个对象将作为属性添加。你传入instanceUrl第一个哈希,它被认为是一个属性。请参阅此小提琴的演示:http: //jsfiddle.net/nikoshr/GADW7/

使用第二个对象来声明您的选项1

var PatientModel = Backbone.Model.extend({
    url: function() {
        return this.instanceUrl;
    },
    initialize: function(attrs, options) {
        this.instanceUrl = options.instanceUrl;
    },
    defaults: {
        "person": "",
        "identifiers":""
    }
});

你会把它实例化为

var patientModel = new PatientModel({}, {instanceUrl: '/patient'});

还有一个演示http://jsfiddle.net/nikoshr/GADW7/1/


1:注意,我设置instanceUrl为实例的成员,用全局变量到处乱转,甚至限制在你的模块,势必会引起困扰

于 2013-09-13T07:49:12.883 回答