Just getting started with Backbone. I have a generic view that can render a collection as a list with a title. I’m currently passing the collection and title into the render method, but that seems a bit odd. Is there another way that’s more canonical?
E.g.:
var ListView = Backbone.View.extend({
template: _.template([
"<div>",
"<% if (title) { %><h2><%= title %></h2> <% } %>",
"<% if (items.length > 0) { %>",
"<ul>",
"<% items.each(function(item) { %>",
"<%= itemTemplate(item) %>",
"<% }); %>",
"</ul>",
"<% } else { %><p>None.</p><% } %>",
"</div>"
].join('')),
itemTemplate: _.template(
"<li><%= attributes.name %> (<%= id %>)</li>"
),
render: function(items, title) {
var html = this.template({
items: items /* a collection */,
title : title || '',
itemTemplate: this.itemTemplate
});
$(this.el).append(html);
}
});
var myView = new ListView({ el: $('#target') });
myView.render(myThings, 'My Things');
myView.render(otherThings, 'Other Things');
You should pass attributes in the
initialize()function:So here you would pass the attributes as an object, like so:
Now you have the values that you passed in accessible throughout this instance, in this.options
To pass in a collection, I recommend making one parent view and one subview:
You should always handle the Models of a Collection, not just the data of the collection.