I am trying to get a simple html page to display the retrieved collection data on the html page. There are no errors being thrown so I cannot tell what I'm doing wrong.
The model, collection, and view are being created properly as I can see them in the console with the data that's being retrieved from the API, however the page is not displaying anything on the page. Any help would be greatly appreciated.
Model
Department = Backbone.Model.extend({
idAttribute: "dept_id",
urlRoot: appRouteUrl + '/api/v1/departments',
defaults: {
dept_code: '',
dept_desc: ''
}
});
Collection
DepartmentCollection = Backbone.Collection.extend({
url: appRouteUrl + '/api/v1/departments',
model: Department
});
View
var DepartmentListView = Backbone.View.extend({
template: "#department-list-template",
tagName: "ul",
render: function() {
var results = [];
var compiledTemplate = _.template(this.template);
this.collection.each(function(department) {
console.log(department);
var html = compiledTemplate(department.toJSON());
results.push(html);
});
this.$el.html(results);
return this;
}
});
Index
<!DOCTYPE html>
<html>
<head>
<title>AppName</title>
</head>
<body>
<div class="departments">
<script type="text/template" id="department-list-template">
<span><%= dept_desc %></span>
</script>
</div>
<script>
var departments = new DepartmentCollection();
departments.fetch();
var departmentList = new DepartmentListView({
collection: departments
});
$('.departments').html(departmentList.render().$el);
departmentList.render();
</script>
</body>
</html>
Since you don't have an item view, I think it's best to iterate on the collection view's template. Make sure you create the view instance/call it's render after your collections fetch method succeeds.
Also, you shouldn't add your template inside an element that can be removed.
You are calling the render before the ajax call is finished. just use deferred and call render when fetch is finished.
Try changing html this way
and the view
The underscore template function accepts an html string, but you're giving it an id string. Try
EDIT: using the correct context