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?
source share