Trunk Model: Nested Data Structure

I am developing a basic application that makes a crossdomain support request. The nested data structure in the request is required, in the curl request I have this 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 do not have a nested structure, and this is quite convenient, because I use the image model field in view (creating a DOM element).

What is the correct way to send embedded data to a server from a Backbone application?

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: '' }, }); 

Part of the view using the 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}); }); }, 

Part of another view that sends data to the 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(); } 
+6
source share
1 answer

The first parameter you pass to save is a hash of the attributes that will be passed in your save.

In your sendTo function sendTo simply create an object with data from your model and any additional form values ​​in the way that the server expects. By default, when the save is successful, the data from the response will be transmitted through the parsing method and return to the model.

 var myData = { //create nested object for the server }; this.model.save(myData); 
+1
source

Source: https://habr.com/ru/post/905398/


All Articles