我正在使用下面的代码尝试将一组书籍加载到HTML模板中。
数据结果显示在我的控制台中,但我无法弄清楚它们为什么没有出现在我的HTML模板中。
我从着陆页开始,使用此调用创建下面的视图:
var sv = new BookSearchView();
其中BookSearchView.js是以下代码:
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>
答案 0 :(得分:1)
我可能错了,但似乎在您的模板中传递了model.toJSON对象,但模板中没有变量来使用此值或渲染它。
所以每次模板都将返回"<div class="Book"></div>"
,这将在html页面上显示任何内容。