I am having some difficulties rendering a Backbone Collection View.
In my HTML, I have a div with id member-list
:
<div id="member-list"></div>
The view used to hold the actual list is called MemberListView
:
var Backbone = require('backbone');
var $ = require('jquery');
var MemberListItemView = require('MemberListItemView');
return Backbone.View.extend({
tagName: 'ul',
render: function () {
this.collection.each(function (item) {
this.$el.append(new MemberListItemView({ model: item }).render().el);
}.bind(this));
return this;
},
});
Each single item is represented by MemberListItemView
:
var Backbone = require('backbone');
var $ = require('jquery');
var _ = require('underscore');
return Backbone.View.extend({
template: '_.template($("#memberItemTemplate").html())',
tagName: 'li',
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
});
From a parent view, I invoke MemberListView
like this:
this.list = new MemberListView({ collection: this.collection });
this.list.setElement('#member-list').render();
Unfortunately, the HTML output is not correct, the ul
is missing:
<div id="member-list">
<li>Member</li>
<li>Member</li>
<li>Member</li>
</div>
I think the problem has something to do with using setElement
- probably because there is already el
or something like this.
How can I add the <ul>
to the output and force MemberListView
to not ignore the tagName
?
return Backbone.View.extend({
template: '_.template($("#memberItemTemplate").html())',
Your tempalte seems to be a string and not a tempalte. I am guessing what you want is something like this:
return Backbone.View.extend({
template: _.template($("#memberItemTemplate").html()),
also instead of
this.list = new MemberListView({ collection: this.collection });
this.list.setElement('#member-list').render()
try
this.list = new MemberListView({ collection: this.collection, el: $('#member-list') });
this.list.render();