【发布时间】:2017-08-23 13:35:08
【问题描述】:
我已编辑此问题,因为人们将我指向此链接:-
uncaught TypeError: Cannot call method 'replace' of undefined backbone.js
但我认为这两个问题是不同的,这里提供的解决方案也已经实现。人们还提到代码正在他们的终端上运行,如果您在您的机器上执行此代码,请点击Home Page 链接,让我知道您的首页视图是否正在加载。
实际问题
我是 Backbone.js 的新手,目前正在阅读教程。我看到不同的开发人员使用不同的方式来完成一项任务,所以我尝试混合匹配他们的方法来更深入地理解它并有一个清晰的概念。我在我的代码中试图实现的是使用路由器执行切换视图,这就是我的代码的外观(我已将其精简为基础,以便于调试)-
<script type="text/template" id="home-template">
<h1>This is the home page</h1>
</script>
<script type="text/javascript">
var HomeView = Backbone.View.extend({
tagName: 'div',
initialize: function() {
$("body").html(this.el);
this.template = _.template($('#home-template').html());
this.render();
},
render: function() {
this.$el.html(this.template());
}
});
var AppRouter = Backbone.Router.extend({
routes: {
'home': 'home'
},
home: function() {
this.view = new HomeView();
}
});
var appRouter = new AppRouter();
Backbone.history.start();
</script>
<a href = "#/home">Home Page</a> <br />
所以当我加载页面时它加载正确,但是当我点击Home Page 链接时,它在该行中出现 JS 错误 -
this.template = _.template($('#home-template').html());
我还添加了我面临的问题的屏幕截图。对于这种错误,我查看了 stackoverflow 中给出的解决方案,并根据建议的更改修改了我的代码,但没有奏效。问题是,_.template 函数无法识别home-template 模板。知道为什么会这样以及如何解决吗?
【问题讨论】:
-
当我用
this.template = _.template("<h1>This is the home page</h1>");替换行this.template = _.template($('#home-template').html());时,它按预期工作。所以我很确定我面临的错误是因为home-template是不可见的。 -
@Louis 如果您看到答案中提供的两种解决方案,我已经应用了这两种解决方案。我已经调整了模板的
<script>订单以及created the compiled template function in the initialize。你看到我在这里错过了什么吗?如果有,请指出。 -
当您点击链接
Home Page时,您究竟看到了什么?主页视图是否在有标题的地方加载? -
@Louis 你没有收到错误,因为我删减了代码,只放了错误的部分。我已经修改了我的代码,并在它试图呈现
Home View的位置添加了另一位。立即尝试,看看您是否收到错误。同样要复制错误,如上所述,您必须单击Home Page链接。
标签: jquery backbone.js underscore.js underscore.js-templating