I\'m trying to render an html table using underscore template engine. First I have the JSON response from the server like this
{
CurrentModel: {
First, I would parse the data into the collection to get a list of the pages and maybe grab the CurrentModel
definition :
var PageCollection = Backbone.Collection.extend({
url: '/pages',
model: Page,
parse: function(response) {
this.CurrentModel=new Page(response.CurrentModel);
return response.Children;
}
});
Then, with the row template set up as
<script id="tpl-page-list-item" type="text/template">
<tr>
<td><%= Metadata.Name %></td>
<td><%= Metadata.Slug %></td>
<td><%= Metadata.IsPublished %></td>
<td><%= Metadata.Changed %></td>
<td><input type='checkbox' /></td>
</tr>
</script>
you can define your views more or less like you had them
var PageListItemView = Backbone.View.extend({
template: _.template($('#tpl-page-list-item').html()),
events: {
"click input[type=checkbox]": "publish"
},
render: function (eventName) {
var html=this.template(this.model.toJSON());
this.setElement($(html));
return this;
},
publish: function () {
console.log(this.model.get("Metadata").Name);
}
});
var PageListView = Backbone.View.extend({
tagName: 'table',
initialize: function () {
this.collection.bind("reset", this.render, this);
},
render: function (eventName) {
this.$el.empty();
this.collection.each(function(page) {
var pageview=new PageListItemView({ model: page });
var $tr=pageview.render().$el;
this.$el.append($tr);
},this);
return this;
}
});
Initialize the collection and the views, fetch the data, and you should have something equivalent to this Fiddle : http://jsfiddle.net/NtmB4/
var coll=new PageCollection();
var view=new PageListView({collection:coll})
$("body").append(view.render().el);
coll.fetch();
And a Fiddle corresponding to your full template http://jsfiddle.net/NtmB4/2/