[英]Why is Backbone.js looking for the template before I render the view?
I'm new to Backbone.js and I'm writing a small app. 我是Backbone.js的新手,并且正在编写一个小应用程序。 I decided to structure everything related to each resource (books, authors) in separate files (books.js, authors.js).
我决定在单独的文件(books.js,authors.js)中构建与每种资源(书籍,作者)相关的所有内容。 Each file features four BBjs classes: a model, a collection, a model view and a collection view corresponding to the given resource.
每个文件具有四个BBjs类:与给定资源相对应的模型,集合,模型视图和集合视图。 This was working fine when only one of this files was to be included.
当仅包含此文件之一时,此方法工作正常。
Now I'm working on a screen that should show a book collection in a specific author page. 现在,我正在一个屏幕上,该屏幕应在特定的作者页面上显示一个藏书。 I do not intend to render any of the author views, but only to use the author model.
我不打算呈现任何作者视图,而只是使用作者模型。 However, Backbone is failing with
Uncaught TypeError: Cannot read property 'replace' of undefined (underscore.js)
because it's looking for a template that's not present on this page. 但是,Backbone失败,出现
Uncaught TypeError: Cannot read property 'replace' of undefined (underscore.js)
因为它正在寻找此页面上不存在的模板。
My author view class looks like this: 我的作者视图类如下所示:
app.AuthorView = Backbone.View.extend({
...
template: _.template( $('#book-table-row-template').html() ),
...
render: function(e) { ... }
});
The page does not feature any #book-table-row-template
element (I guess that's what triggering the error) but I'm not even instantiating this view. 该页面不包含任何
#book-table-row-template
元素(我想这就是触发错误的原因),但是我什至没有实例化此视图。 What am I doing wrong? 我究竟做错了什么? Is there any other more productive way to organize my backbone classes?
还有其他更有效的方式来组织骨干课程吗?
You are calling the _.template
function right away. 您正在立即调用
_.template
函数。 It doesn't wait for instantiation. 它不等待实例化。 And if there is no
#book-table-row-template
, jQuery will not find that either. 而且,如果没有
#book-table-row-template
,jQuery也不会找到。
If you want it to wait until instantiation, set this.template
in your initialize
method, like so: 如果您希望它等待实例化,
this.template
在您的initialize
方法中设置this.template
,如下所示:
initialize: function() {
this.template = _.template( $('#book-table-row-template').html() );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.