Backbone, Views, ViewModels, and Rendering - tsgrp/HPI GitHub Wiki
Backbone and knockout out of the box handle rendering and DOM manipulation very differently.
Backbone divides the page into views. Each of the views are rendered and the user sees the page. Typically the view that is rendered has been generated by associating a template with a model and compiling a string of html. If any values change, the code calls render again, which reruns the template and changes what the user sees.
Example: I have an array, my template shows a list of items in the array. I render and see a list of 4 things. Then I add something to the array, an event has been registered (manually) so that if the array changes, the view re-renders. I will now see 5 items in my list.
Knockout on the other hand, works differently. Knockout uses bindings that know how to react to specific bindings and change the html accordingly. So when you bind a section of the DOM to a viewmodel, the bindings are listening and they know how to 'render' themselves.
Take for instance the same scenario above. Say that you have a foreach binding on a list that is bound to an observableArray. If that array changes, Knockout's foreach binding has logic that can determine what changed and update the DOM accordingly. As an aside, this is why Knockout claims it is more efficient; it makes a minimal set of changes to the DOM, whereas Backbone will just re-render the entire unordered list and every list item to add an item. Knockout just creates the new list item element and adds it to the unordered list, leaving the existing ones where they are.
Right now, HPI takes a mix and match approach. You can use the Handlebars templates and Backbone, or you can use Knockout. In most cases Knockout will be the way to go, but there are arguments for Backbone in some specific scenarios. For now, let's assume you'll be using Knockout.
The other piece of HPI is the layout manager, which gives us an easy way to manage views. The entire page is represented by a layout, which is divided into subviews. Each subview can have subviews of it's own. A good rule of thumb is that you when using viewmodels and Knockout, you want to apply bindings only on views that have NO subviews.
Say a layout is composed of views A, B, and C. B has sub views 1 and 2. C has subviews X and Y. X has subview 3.
You can apply bindings to: A, 1,2, Y, and 3.
It is imperative you do not render more than once any view that applies bindings, or any view who's subviews apply bindings. This is because calling myView.render() renders myView and all its subviews. To keep it simple: don't call applybindings in any View where you are also calling setView(). Only apply bindings in views that do not have subviews.