I've got this Backbone.Model
representing a Google Books API volume:
var Book = Backbone.Model.extend({
defaults: {
volumeInfo : {
title: 'n.a.',
authors: 'n.a.',
publisher: 'n.a.',
publishedDate: 'n.a.',
imageLinks : {
smallThumbnail: '/unavailable.jpg'
}
}
},
parse: function(resp) {
if (resp.volumeInfo.authors) {
resp.volumeInfo.authors = resp.volumeInfo.authors.join(',');
}
return resp;
}
});
Which is fed to 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>
Upon parsing the template, when a volume JSON does not contain an imageLinks
I receive this error:
Uncaught TypeError: Cannot read property 'smallThumbnail' of undefined.
I know I could fix it by checking with an if
in the Model
or in the template
but what's the purpose of defaults
model property then? Does that work only if not overriding parse
?