user2528222
user2528222

Reputation: 97

to save a complicated model in backbone

I have a model data like:

{
    "status": 7, 
    "organizations": [{
        "org_address": "\u4e2d\u56fd\u5317\u4eac\u5e02\u671d\u9633\u95e8\u59161001\u53f7",
        "job_positions": "\u603b\u7ecf\u7406", 
        "org_id": 11, 
        "org_name": "\u6570\u7ef4\u79d1\u6280"
    }], 
    "first_name": null, 
    "last_name": null, 
    "create_date": "2013-07-02 23:47:14.239000", 
    "name": "\u5f20\u5174\u6807", 
    "extra_emails": [null], 
    "tags": [{
        "oid": 4, 
        "id": 4, 
        "name": "friend"
    }], 
    "nick_name": "\u9ec4\u98de\u9e3f", 
    "gender": "\u7537", 
    "image": null, 
    "created_by": "system", 
    "effective_start_date": "2013-07-02 23:47:14.239000", 
    "social_medias": [{
        "url": "http://weibo.com/12345",
        "sm_name": "\u6700\u70ab\u6c11\u65cf\u98ce", 
        "type": "\u65b0\u6d6a\u5fae\u535a", 
        "party_sm_id": 1
    }], 
    "date_of_birth": "1980-04-01", 
    "extra_phones": {
        "office_phone": "82323333", 
        "fax": "82324433"
    }, 
    "mobile_phone": "13909609306", 
    "primary_email": "[email protected]", 
    "id": "10", 
    "isUser": false
}

Now I want to modify the data and save the model, suppose my model is named "cmodel". When I attempt to save the data, I have tried the following:

cmodel.save({
    organizations[0].org_address:"road1",
    organizations[0].org_name:"name1"
});

However this didn't work, so I want to know how to save my edited data.

Hope for your help, thank you.

Upvotes: 1

Views: 99

Answers (1)

dcarson
dcarson

Reputation: 2853

I was curious to see if mu is too short's answer/comment would work, because it would have been a godsend! I'd have gone and changed much of my own code :)

However if you try to save your model as he suggests, it will unfortunately merge a new attribute into your model named "organizations[0].org_address". You can see this in this fiddle.

So... If you have an attribute of your model that is an array and you want to edit and save individual elements of the array, the way to do it is to clone the whole array, change the elements that you want, then pass the cloned array to the save function like this

var orgClone = _.clone(cmodel.get("organizations"));

orgClone[0].org_address = "road1";
orgClone[0].org_name = "name1";

cmodel.save({organizations: orgClone });

It is important to note that the underscore clone function is a shallow copy only. If you have a model attribute that is a complex object with nested arrays/objects, it would be wise to roll your own clone function or use jQuery extend to get a deep clone as follows:

var orgClone = $.extend([], cmodel.get("organizations"));

Upvotes: 2

Related Questions