Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I have the very same issue while I'm writing my Backbone application. Having to deal with embedded/nested models. I did some tweaks that I thought was a quite elegant solution.</p> <p>Yes, you can modify the parse method to change a attributes around in the object, but all of that is actually pretty unmaintainable code IMO, and feels more of a hack than a solution.</p> <p>Here's what I suggest for your example:</p> <p>First define your Layout Model like so.</p> <pre><code>var layoutModel = Backbone.Model.extend({}); </code></pre> <p>Then here's your image Model:</p> <pre><code>var imageModel = Backbone.Model.extend({ model: { layout: layoutModel, }, parse: function(response){ for(var key in this.model) { var embeddedClass = this.model[key]; var embeddedData = response[key]; response[key] = new embeddedClass(embeddedData, {parse:true}); } return response; } }); </code></pre> <p>Notice that I have not tampered with the model itself, but merely pass back the desired object from the parse method.</p> <p>This should ensure the structure of the nested model when you're reading from the server. Now, you would notice that saving or setting is actually not handled here because I feel that it makes sense for you to set the nested model explicitly using the proper model.</p> <p>Like so:</p> <pre><code>image.set({layout : new Layout({x: 100, y: 100})}) </code></pre> <p>Also take note that you are actually invoking the parse method in your nested model by calling:</p> <pre><code>new embeddedClass(embeddedData, {parse:true}); </code></pre> <p>You can define as many nested models in the <code>model</code> field as you need.</p> <p>Of course, if you want to go as far as saving the nested model in its own table. This wouldn't be sufficient. But in the case of reading and saving the object as a whole, this solution should suffice.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload