尝试呈现布局视图时无法读取未定义的 属性 'render'

Cannot read property 'render' of undefined while trying to render a layout view

我正在 Backbone.js 中编写一个简单的应用程序,我有一个布局视图来呈现其中的所有其他视图。在我的 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();
});

但每次我尝试导航到某个地方或只是启动默认页面时,控制台 returns 都会出现以下错误:

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 需要将子视图传递到其渲染函数中。

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();
});

它应该从那里开始工作。