Javascript 在使用动态url初始化时保存主干模型
我有一个主干模型,如下所示Javascript 在使用动态url初始化时保存主干模型,javascript,backbone.js,Javascript,Backbone.js,我有一个主干模型,如下所示 define([], function(){ var instaceUrl; var PatientModel = Backbone.Model.extend({ url: function() { return instanceUrl; }, initialize: function(options) { instanceUrl = options.ins
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
构造函数/初始化新模型([属性],[选项])
传递的第一个对象将作为属性添加到其中。在第一个散列中传递instanceUrl
,它被认为是一个属性。请参见此小提琴的演示:
使用第二个对象声明您的选项1:
您可以将其实例化为
var patientModel = new PatientModel({}, {instanceUrl: '/patient'});
还有一个演示
1:请注意,我将
instanceUrl
设置为实例的一个成员,使用一个全局变量,甚至仅限于您的模块,必然会导致后续问题
var patientModel = new PatientModel({}, {instanceUrl: '/patient'});