AlexNikolaev94
AlexNikolaev94

Reputation: 1209

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

I'm writing a simple app in Backbone.js and I've got a layout view to render all the other views inside it. In my index.html file I've got the following:

<section id="layout">
    <section id="outlet"></section>
</section>

In my layout.js I've got this:

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

In my router.js I have the following code:

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

Finally in main.js I have this:

$(document).ready(function () {
    var layout = new LayoutView().render();
    var router = new AppRouter({layout: layout});
    Backbone.history.start();
});

But every time I try to navigate somewhere or just start the default page the console returns me the following error:

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

Upvotes: 0

Views: 1682

Answers (1)

Clarence Leung
Clarence Leung

Reputation: 2556

Your LayoutView expects a child view to be passed into its render function.

render: function (view) {
    if (this.child) this.child.remove();
    this($('#outlet').html((this.child = view).render().el);
    return this;
}

But in your main.js file, you're calling render with no parameters.

var layout = new LayoutView().render();

render() should be called by your AppRouter, so if you just change it to:

$(document).ready(function () {
    var layout = new LayoutView();
    var router = new AppRouter({layout: layout});
    Backbone.history.start();
});

It should work from there.

Upvotes: 1

Related Questions