Backbone model: nested data structure

2019-06-19 02:06发布

I'm developing backbone app, which makes crossdomain restful request. The nested data structure in request are required, in the curl request I have that structure:

{
    "site_id": 1,
    "post": {
        "site_id": 1,
        "provider_id": 1,
        "provider_post_id":1,
        "created_ts": "12.12.12",
        "post": {
            "header": "text",
            "caption": "text",
            "image": "http://...jpg"
        }
    }
}

In the model I have not nested structure and this is pretty comfortable, because I use image model field in the view (DOM element creation).

What the correct way to send nested data to server from Backbone app?

Model:

var WraperModel = Backbone.Model.extend({
    url: 'http://mydomain/core/api/v1/bookmarklet_post/?  callback=?',
    defaults: {
        site_id: 1, // shouldn't be hardcoded
        type:"type", site_id:2, provider_id: 2, provider_post_id: 2,  created_ts:2,
        header : '',
        caption: '',
        image: ''
    },
});

The part of view, which use image model property:

drawItem: function (model) {
    var inst = new ImageView({model: model, tagName: 'li',     className:'images-item'}).render();
    this.imagesWrapper.append(inst.el);
},
getImages: function () {
   var images = doc.getElementsByTagName('img'),
       view = this;
   _.each(images, function (image) {
       image.offsetHeight > 75 
       && image.offsetWidth > 75 &&
       view.collection.add({image: image.src});
   });
},

The part of another view, which send data to server.

sendTo: function(){
    var that = this,
    data = {saving: true};

    $('#add-header').val() && (data.header = $('#add-header').val());
    $('#add-description').val() && (data.caption = $('#add-description').val());
    this.model.set(data);
    this.model.save();
}

1条回答
我只想做你的唯一
2楼-- · 2019-06-19 02:50

the first parameter you pass in save is a hash of the attributes that are going to be passed along in your save.

In your sendTo function just build up an object with the data from your model and any additional form values in a way that the server expects. By default, when a save is successful the data from the response will be passed through the parse method and set back on the model.

var myData = {
     //create nested object for the server
};

this.model.save(myData);
查看更多
登录 后发表回答