我正在 Backbone.js 中编写一个简单的应用程序,并且我有一个布局 View 来渲染其中的所有其他 View 。在我的 index.html
文件中,我有以下内容:
<section id="layout">
<section id="outlet"></section>
</section>
在我的 layout.js
中,我有这个:
var LayoutView = Backbone.View.extend({
el: '#layout',
render: function (view) {
if (this.child) this.child.remove();
this($('#outlet').html((this.child = view).render().el);
return this;
}
});
在我的 router.js
中,我有以下代码:
var AppRouter = Backbone.Router.extend({
routes: {
'': 'home'
},
initialize: function (options) {
this.layout = options.layout;
},
home: function () {
// renders a collection view
this.layout.render(new ResumeList({collection: resumes}));
}
});
最后在 main.js
中我有这个:
$(document).ready(function () {
var layout = new LayoutView().render();
var router = new AppRouter({layout: layout});
Backbone.history.start();
});
但是每次我尝试导航到某个地方或只是启动默认页面时,控制台都会返回以下错误:
jQuery.Deferred exception: Cannot read property 'render' of undefined TypeError: Cannot read property 'render' of undefined
at n.render (http://localhost:8080/js/views/layout.js:5:51)
at HTMLDocument.<anonymous> (http://localhost:8080/js/main.js:2:35)
at j (http://localhost:8080/node_modules/jquery/dist/jquery.min.js:2:29948)
at k (http://localhost:8080/node_modules/jquery/dist/jquery.min.js:2:30262) undefined
jquery.min.js:2 Uncaught TypeError: Cannot read property 'render' of undefined
最佳答案
您的 LayoutView 期望将 subview 传递到其渲染函数中。
render: function (view) {
if (this.child) this.child.remove();
this($('#outlet').html((this.child = view).render().el);
return this;
}
但是在您的 main.js
文件中,您调用的是不带参数的渲染。
var layout = new LayoutView().render();
render()
应该由您的 AppRouter 调用,因此如果您将其更改为:
$(document).ready(function () {
var layout = new LayoutView();
var router = new AppRouter({layout: layout});
Backbone.history.start();
});
它应该从那里开始工作。
关于javascript - 尝试渲染布局 View 时无法读取未定义的属性 'render',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39892034/