Search code examples
javascriptbackbone.jsmodels

Model shows as undefined when render is called at event


I have a view with the following initialize method:

initialize: function(){
    this.model.on("all", this.render)
},

And in the render method I access the model's content using:

var contents = this.model.attributes.content;

The content property of the model is an array.
So when I add something to the array using model.set() through the console, the render method is called, but I get the following error :Uncaught TypeError: Cannot read property 'attributes' of undefined(…).
But after adding if I call view.render() manually, it renders the model nicely.
Again if I add anything, it throws the same error.
Solutions?


Solution

  • The problem could be the context ( the value of this ) in which the render is executed - due to the event trigger.

    If you would put a debugger and examine the value of this inside the render which gets executed by the model change, it would not be holding the reference of view.

    You can get this fixed by passing a third parameter to the on as specified in backbone documentation:

    this.model.on( 'all', this.render, this );
    

    The third parameter is the context in which the render would be executed. Meaning, whatever you pass as the third parameter, would be the value of this inside the render function.

    It's better to use listenTo instead of on as it cleans up the events in a better way than on does. You can read nice explanation for the same thing here at stackoverflow question Backbone js .listenTo vs .on.

    So the initialize would be written as:

    initialize: function() {
        this.listenTo( this.model, 'all', this.render );
    }
    

    And also, I would recommend to use the get method available in model to access it's attribute, hence instead of accessing content by this.model.attributes.content use this.model.get( 'content' ).

    Hope it helps :)