This is not a specific code-based question. I’m looking for some intuition here with respect to view-model binding in backbone.
Imagine I have a simple person model with properties id, First and Last name. Then I have a collection of said models returned from a JSON web service. I understand how to retrieve and update a given item via sync using backbone. Where I feel sloppy is in my binding of views and models — this is where I need a good explanation and some help on best practices.
When I create my view for a list of people, I show each person in a div with the class of the div containing TWO classnames: one named “personclass” and the other with the id of that person. Registering click event for “personclass” lets me grab the ‘other’ class – which is the id – then use that in a hash to manipulate the specific person (the underlying model of that person).
My manual view-model binding by referencing class names feels incredibly sloppy and I sense that I’m missing something fundamental about backbone. Quality of examples out there vary, so I will be grateful for a clean and easy explanation here.
There’s nothing necessarily wrong with this approach. It can be quite beneficial when you have a memory constrained environment, for example.
Another approach, though, is to render a new Backbone.View for each item in your collection. Then each view instance can be specifically focused on the one item that it is displaying. You won’t have to worry about adding the model’s id to the rendered HTML, either.
I wrote an article a while back that explains both of these scenarios, shows how to accomplish each, and gives pros and cons of them:
http://lostechies.com/derickbailey/2011/10/11/backbone-js-getting-the-model-for-a-clicked-element/