Reputation: 7102
I am using the code below to try and load a collection of books into an HTML template.
The data results do show up in my console, but I can't figure out why they are not showing up in my HTML templates.
I start off on a landing page and create the views below with this call:
var sv = new BookSearchView();
Where BookSearchView.js is the code below:
define(['underscore', 'backbone', 'jquery', 'text!BookSearchResults.html', 'text!Book.html', 'jquery-ui'],
function (_, Backbone, $, tmplBooks, tmplBook) {
'use strict';
//book model
var Book = Backbone.Model.extend({
urlRoot: 'api/search'
});
//book collection with URL to web query [this part works fine]
var BookCollection = Backbone.Collection.extend({
model: Book,
url: '/api/search/fantasy' //this loads a JSON string of fantasy books
});
//create my book collection
var Books = new BookCollection();
Books.fetch().done(function() {
});
//main view
return Backbone.View.extend({
el: '#search_container',
className: 'Books',
template: _.template(tmplBooks, null, { variable: 's' }),
initialize: function () {
this.BookCollection = Books;
},
render: function () {
//loop through my book collection
this.BookCollection.each(function(e) {
this.renderBook(e);
}, this);
return this;
}
//render each book in the collection
renderBook: function (e) {
var self = this;
var bookView = new BookView({
model: e,
parent: self,
});
this.$('#book_container').append(bookView.render().$el);
console.log('Book view: ', bookView); //I can see the data in my console!
}
});
//book view
var BookView = Backbone.View.extend({
tagName: 'div',
className: 'Book',
template: _.template(tmplBook),
initialize: function (args) {
this.parent = args.parent;
this.listenTo(this.model, 'sync change', this.render);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
});
<!--tmplBooks = BookSearchResults.html = search results template-->
<div id="book_container">
<div class="Books">
Search Results:
</div>
</div>
<!--tmplBook = Book.html = individual book template-->
<div class="Book"></div>
Upvotes: 0
Views: 52
Reputation: 145
I may be wrong but it seems that in your template you are passing the model.toJSON object but there is no variable in template to consume this value or render it.
So each time the templete will be returning "<div class="Book"></div>"
which will show nothing on html page.
Upvotes: 1