我正在尝试使用此article中的Derick Bailey的建议来管理主干中的页面转换,但是关于路由不会呈现。它只使用app.BookListView呈现主路由,当我单击以访问about路由时,它将保留app.BookListView。
这是我的代码:
HTML
<section class="feed">
</section>
<script id="bookTemplate" type="text/template">
<div class="book">
</div>
</script>
<script id="aboutTemplate" type="text/template">
<div class="about">
Bla bla bla bla
</div>
</script>
观点
Backbone.View.prototype.close = function(){
this.remove();
this.unbind();
};
function AppView(){
this.showView(view) {
if (this.currentView){
this.currentView.close();
}
this.currentView = view;
this.currentView.render();
$('.feed').html(this.currentView.el);
}
};
app.BookView = Backbone.View.extend ({
tagName: 'div',
className: 'book',
template: _.template( $( '#bookTemplate' ).html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
)};
app.BookListView = Backbone.View.extend({
el: '.feed',
initialize: function ( initialBooks ) {
this.collection = new app.BookList (initialBooks);
this.render();
},
render: function() {
this.collection.each(function( item ){
this.renderBook( item );
}, this);
},
renderBook: function ( item ) {
var bookview = new app.BookView ({
model: item
})
this.$el.append( bookview.render().el );
}
});
app.AboutView = Backbone.View.extend({
tagName: 'div',
className: 'about',
template: _.template( $( '#aboutTemplate' ).html()),
render: function () {
this.$el.html(this.template());
return this;
}
});
路由器
var AppRouter = Backbone.Router.extend({
routes: {
'' : 'home',
'about' : 'about'
},
initialize: function(options){
this.AppView = options.AppView;
},
home: function () {
var homeView = new app.BookListView();
this.AppView.showView(homeView);
},
about: function () {
var aboutView = new app.AboutView();
this.AppView.showView(aboutView);
}
});
app.Router = new AppRouter();
Backbone.history.start();
测试BookView的一些数据:
$(function(){
var books = [
{title:'Imperial Bedrooms'},
{title:'Less than Zero'},
];
new app.BookListView (books);
JSFiddle:http://jsfiddle.net/swayziak/xdRRE/
控制台抛出此错误:
未捕获的SyntaxError:意外的令牌{,在“this.showView(view){”
未捕获的TypeError:无法在“this.AppView = options.AppView”中读取未定义的属性“AppView”
感谢。
答案 0 :(得分:4)
您有语法错误,....错位或缺少字符,未定义的对象。
new app.BookListView (books);
&lt; - 这应该是:
var bookListView = new app.BookListView (books);
以下内容无效:
this.showView(view) {
if (this.currentView){…
我猜你想要这个吗?
this.showView = function(view){…}
以下行也会引发错误:
app.BookView = Backbone.View.extend ({…)};
应该是:
app.BookView = Backbone.View.extend ({…});
下一行工作:
this.AppView.showView(homeView);
你必须在初始化时传递appview
:
app.Router = new AppRouter(appView);
我会尝试清理你的小提琴,你使用什么样的代码编辑器?因为所有错误都与语法有关。
<强>更新强>
这是一个fiddle
你家乡路线的问题就在这条线上:
home: function () {
if(!this.bookListView){
this.bookListView = new app.BookListView();
}
},
应该是:
home: function () {
if(!this.bookListView){
this.bookListView = new app.BookListView(books);
}else{
this.bookListView.render();
}
},