我有一个骨干模型,如下所示
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
作为模型属性?
对于该方法签名模型构造函数/初始化方法是
构造函数/初始化新模型([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
为实例的成员,使用全局变量(甚至仅限于您的模块)也必然会导致麻烦
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句