Traditional Backbone.js templates typically interpolate a few values and have a little basic logic, but even the simplest of these templates knows too much. It is the view’s responsibility to manage logic, events, and the relationship with models while the template should simply manage the HTML markup.
Enter the static template. It does not contain any logic or even interpolated values. In fact, a static template does not contain any executable code at all, it is just markup.
A static template and its view might look like this:
Keeping all that logic in the view has several key advantages:
- Easier to test
Keeping all the logic in the view makes it much easier to test-drive that behavior. This in turn increases the quality of your code and gives you greater confidence to build and refactor.
- Doesn’t break event bindings
With traditional templates, re-rendering creates new DOM elements which requires re-binding events. The DOM for static templates, on the other hand, is only rendered once. This spells the end of your event re-binding troubles.
- Faster re-rendering
Static templates can significantly improve your re-rendering speeds. Rendering traditional templates was an all-or-nothing decision. However, By encapsulating all the logic into methods on the view, this becomes a much more granular decision. Arbitrary sections can be ’re-rendered' in response to events.
By keeping a strong separation of concerns between your views and templates, you end up with code that is cleaner, more modular, more readable, more performant, and easier to maintain. Give it a try, you will be surprised by the power and simplicity of this approach.
Learn more about Backbone best practices in our book Backbone.js on Rails.