Backbone.js Model defaults and parse -
i've got backbone.model
representing 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 fed 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 template, when volume json not contain imagelinks
receive error:
uncaught typeerror: cannot read property 'smallthumbnail' of undefined.
i know fix checking if
in model
or in template
what's purpose of defaults
model property then? work if not overriding parse
?
a few things. first, shouldn't have nested objects backbone model attributes in general - can ok if can treat attribute atomically, perfect example of when can't. data-model perspective, imagelinks should own backbone model class, should volumeinfo.
second, if defaults object literal ({}
) instead of function, same object used default attrs each model instance. think want this:
defaults: function(){ return { volumeinfo : {} // should new volumeinfo({}) imo }; },
but data model bigger issue - .defaults doesn't kind of nested-object-template thing seem going for, , reason: doesn't work well, first of many gotchas you'll run if don't keep instance data pretty flat.
Comments
Post a Comment