Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: calling render() from view's Initialize: function

I want to my view to render itself when it is first created, so I am calling this.render(); in the initialize: function, like this (some code removed):

var MyView = Backbone.View.extend({

    el: $("#mydiv"),

    initialize: function() {
        this.render();
    }
...

In the render: function I'm then looping through a child collection, and appending the rendered views of each child element:

render: function() {
    this.model.somecollection.forEach(function(c) {
        var view = new ChildView({ model: c });
        this.el.append(view.render().el); //*****
    });
    return this;
},

The problem I'm having is that that the reference to this in the render function (marked with asterisks) is set to window rather than the MyView object, and it's causing an error.

I assume I am calling render incorrectly (currently this.render(); ). How should I be doing this so that the this context is preserved?

like image 208
UpTheCreek Avatar asked Dec 01 '22 07:12

UpTheCreek


2 Answers

Save this outside the for loop.

var that = this;

this is not transported inside the loop if you use _.each().

like image 183
ZeissS Avatar answered Dec 18 '22 00:12

ZeissS


In Javascript, whenever you enter a new function context, the value of this has likely changed. All you need to do is store the value of this before you enter the function:

render: function() {
    var self = this;
    this.model.somecollection.forEach(function(c) {
        var view = new ChildView({ model: c });
        self.el.append(view.render().el); //*****
    });
    return this;
},
like image 26
Skylar Anderson Avatar answered Dec 17 '22 23:12

Skylar Anderson