I’m building my first web app using Backbone.js. So far so good. I’m looking for a little guidance:
I have a <ul> that I want to populate with <li> that represent ‘products’
This is what I’ve defined so far:
- 1 model -> product
- 1 collection -> products
- 1 view -> view_product (view that represents a single product — one
<li>)
I’ve created an instance of the collection by passing it an array of objects that represent my products, I understand this creates instances of the model for each product inside the collection.
I’m confused about what to do next.
Should I loop over the collection with _.each(), create and instance of view_product for each model in products and then try to append them to my <ul>? Something tells me that’s the wrong idea.
You understand correctly.
You’ll probably want to add one more view for the collection of products, this view would be a
<ul>and it would manage the per-product views (which are<li>s):Collections already have many Underscore methods mixed in so you don’t need to
_.each(collection.models, ...),collection.each(...)works just as well and is more idiomatic.Then you’d instantiate and render one of your per-collection views:
Backbone treats
collectionoptions to views specially, that’s wherethis.collectioncomes from ininitialize.The per-product views would take care of binding to the product’s events (such as name, price, quantity, … changes) and would take care of adding/removing products from the person’s cart. The per-collection view is responsible for anything involving the collection as a whole: collection resets, new products are added, products are removed, …
Here’s a quick’n’dirty demo to help illustrate what I’m talking about: http://jsfiddle.net/ambiguous/SSstN/1/