Reputation: 1736
I'm learning BackboneJS. I have a few questions. Is it a common thing to rerender the complete view after the contoller or model is changed? And do I need to clear to container at the start of the render function?
Upvotes: 1
Views: 823
Reputation: 5263
1) Re-rendering a complete view is actually easier than updating parts of the view, as long as the view itself is reasonably atomic.
2) No, you don't need to clear container and it has nothing to do with Backbone but with your DOM library, e.g. jQuery, and your templating engine, e.g. Handlebars. So what you do is either
this.$el.html(this.template(data)); // template is a compiled Handlebars template
or
this.$el.html($('<div />').text('Whatever'); // using jQuery
In any case, $el.html
re-inserts HTML to the target element of the view.
Upvotes: 1
Reputation: 10993
First you don't need to clear the container at the start of your render function (unless of course you want to clear the container).
As for your first point, It obviously depends on your circumstances (how complex is the view), but while it may pay sometimes to just rerender the entire view overwriting the previous contents, you don't need to do so. In backbone.js you can listen to changes on particular attributes and then since you have access to the DOM element just update part of the view accordingly.
for example
initialize : function () { _.bind("change:name", nameChanged, this); },
nameChanged: function(event) { this.$el.find('.name').val(this.model.get('name'); }
Upvotes: 1