Search code examples
javascriptjquerybackbone.js

Adding a Collection to a ul in backbonejs


I'm just learning js/backbonejs and I have a simple question, Please feel free to direct me to a duplicate.

I have a Collection, I've populated it and I can access it in the console by doing the standard:

collection1.at(1).get('name');

I can also loop through the values by doing:

for(vars i = 0; i < collection1.size(); i++)
{
console.log(collection1.at(i).get('name'));
}

I have four buttons and have views on them and functions that correctly output something to the console when i click on them. When i click on the Show all button i want to display every model in the collection along with the data it has (id,name,fame);

How would i go about doing this? I know i have to have a

<ul id = "gottaChangeThis"></ul>

How would I be able to add something like this to it:

<li><%=id%><%=name%><%=fame%></li>

Any help or redirection would be helpful, Thanks


Solution

  • The basic architecture could include a Backbone.View that accepts your Collection. On render, iterate through the Models in the collection, and for each one render a different Backbone.View (to render the <li>) and append it to the parent <ul> element.

    As an alternative, consider using Marionette. It's a Backbone framework/extension that gives you additional objects as a means to eliminate a lot of boilerplate. In your case, you'd want a Marionette.CollectionView with a childView specified. This childView could be a Marionette.ItemView, such that when you render the CollectionView, it automagically instantiates and renders a childView for each Model in your Collection.