gpt4 book ai didi

javascript - 使用动态 url 初始化时主干模型保存

转载 作者:行者123 更新时间:2023-11-30 17:52:05 26 4
gpt4 key购买 nike

我有一个 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"
}
]
}

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

最佳答案

model constructor/initialize method 的方法签名是

constructor / initialize new Model([attributes], [options])

传递的第一个对象将被添加为属性。您在第一个哈希中传递 instanceUrl,它被视为一个属性。请参阅此 Fiddle 以获取演示: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设置为实例的成员,绕着一个全局变量转,即使限制在你的模块中,也难免让人心疼下来线路

关于javascript - 使用动态 url 初始化时主干模型保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18780587/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com