I am rendering a single Backbone model in a view. I am using the default underscore template to render the model. How do I handle the "undefined" attribute errors when I am rendering the view (though the model has not loaded)? To clarify, here is an example.
// Using Mustache style markers
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g
};
App.Model = Backbone.Model.extend({});
App.Collection = Backbone.Collection.extend({
model: App.Model
});
App.View = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render');
this.template = _.template($('#model_template').html());
this.model.bind('reset', this.render);
},
render: function() {
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
// HTML
<div id="container"></div>
<script id="model_template" type="text/template">
<strong>Name:</strong> {{ name }} <br/>
<strong>Email:</strong> {{ email }} <br/>
<strong>Phone:</strong> {{ phone }}
</script>
// Run code
var collection = new App.Collection;
var view = new App.View(model: collection.at(0));
$('#container').html(view.render().el);
collection.fetch();
When this code is run, the view is rendered twice, first with an empty model and second when the AJAX query is complete (and 'reset' is triggered). But the issue I am facing is JS stops at the first instance when the model is empty. It gives an error saying the model attribute is undefined.
What am I doing wrong here? Can I suppress the 'undefined' error when the view is rendered in the first instance?