使用动态URL初始化时节省的骨干模型

时间:2013-09-13 07:24:28

标签: javascript backbone.js

我有一个Backbone模型,如下所示

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"
        }
    ]
}

如何避免patientModelinstanceUrl视为模型属性?

1 个答案:

答案 0 :(得分:2)

model constructor/initialize method的方法签名是

  

构造函数/初始化新模型([attributes],[options])

传递的第一个对象将作为属性添加。您在第一个哈希中传递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设置为实例的成员,使用全局变量,甚至限制在您的模块中,必然会导致遇险/ p>