Backbone.js Default Model and Parsing

I have this Backbone.Model representing the Google Books API volume:

  var Book = Backbone.Model.extend({ defaults: { volumeInfo : { title: 'na', authors: 'na', publisher: 'na', publishedDate: 'na', imageLinks : { smallThumbnail: '/unavailable.jpg' } } }, parse: function(resp) { if (resp.volumeInfo.authors) { resp.volumeInfo.authors = resp.volumeInfo.authors.join(','); } return resp; } }); 

What is served in this template:

 <script type="text/template" id="bookCollectionRow"> <tr> <td><img class="thumbnail" src="<%= volumeInfo.imageLinks.smallThumbnail %>" /></td> <td><a target="_blank" href="<%= volumeInfo.canonicalVolumeLink %>"><%= volumeInfo.title %></a></td> <td><%= volumeInfo.authors %></td> <td><%= volumeInfo.publisher %></td> <td><%= volumeInfo.publishedDate %></td> </tr> </script> 

After parsing the template, when the JSON volume does not contain imageLinks , I get this error:

 Uncaught TypeError: Cannot read property 'smallThumbnail' of undefined. 

I know that I can fix this by checking with if in the Model or in the template , but what is the purpose of the defaults model property? Does this only work if parse is not canceled?

+4
source share
1 answer

A few things. Firstly, you should not have nested objects as the basic attributes of the model as a whole - it can be OK if you can always handle the attribute atomically, but this is a great example of when you cannot. From the point of view of the data model, imageLinks should be its own baseline model class, like volumeInfo.

Second, if the default values ​​are an object literal ( {} ) instead of a function, the same object is used as the default attrs for each instance of the model. I think you want this:

 defaults: function(){ return { volumeInfo : {} // should be new VolumeInfo({}) imo }; }, 

But the data model is a big problem..defaults does not make the shadow object template look that you think is appropriate, and for a good reason: it does not work, it will be just the first of many errors that you will encounter if you don't keep your instance data pretty flat.

+10
source

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


All Articles