簡體   English   中英

動態網址初始化時保存骨干模型

[英]Backbone model saving while initialized with dynamic url

我有一個骨干模型,如下所示

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

如何避免將instanceUrl作為模型屬性考慮到patientModel

模型構造函數/初始化方法的方法簽名為

構造函數/初始化新模型([屬性],[選項])

傳遞的第一個對象將添加為屬性。 您在第一個哈希中傳遞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設置為instanceUrl的成員,使用全局變量(甚至僅限於您的模塊)也必然會導致困擾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM