我正在尝试使用 backbone.js 开发一个简单的 RSS 应用程序。我正在使用这个 backbone.js tutorial .定义模板时,第 2 行(模板)出现以下错误。 有人也可以告诉我为什么在教程中定义了 tagName: "li"吗?
uncaught TypeError: Cannot call method 'replace' of undefined backbone.js
Javascript
window.SourceListView = Backbone.View.extend({
tagName:"li",
template: _.template($('#tmpl_sourcelist').html()),
initialize:function () {
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.close, this);
},
render:function (eventName) {
$(this.$el).html(this.template(this.model.toJSON()));
return this;
},
close:function () {
$(this.el).unbind();
$(this.el).remove();
}
});
HTML
<script type="text/template" id="tmpl_sourcelist">
<div id="source">
<a href='#Source/<%=id%>'<%=name%></a>
</div>
</script>
谢谢
最佳答案
你的错误就在这里:
template: _.template($('#tmpl_sourcelist').html()),
_.template
的一部分的内部涉及调用 String#replace
在生成已编译模板函数的过程中未编译的模板文本。该特定错误通常意味着您实际上是在说:
_.template(undefined)
如果没有 #tmpl_sourcelist
就会发生这种情况当你说 $('#tmpl_sourcelist').html()
时在 DOM 中.
有几个简单的解决方案:
- 调整您的
<script>
订购以便您的#tmpl_sourcelist
在您尝试加载 View 之前出现。 在 View 的
initialize
中创建已编译的模板函数而不是在 View 的“类”定义中:window.SourceListView = Backbone.View.extend({ tagName:"li", initialize:function () { this.template = _.template($('#tmpl_sourcelist').html()); //...
至于tagName
去,fine manual有这样的话:
el
view.el
[...]
this.el
is created from the view'stagName
,className
,id
andattributes
properties, if specified. If not, el is an emptydiv
.
所以在你看来是这样的:
tagName: 'li'
表示Backbone会自动创建一个新的<li>
元素作为 View 的 el
.
关于javascript - 未捕获的类型错误 : Cannot call method 'replace' of undefined backbone. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14826149/