javascriptbackbone.jsviewrendering

Backbone.js view render error


If I do this - every thing works great -

var UserList = Backbone.View.extend({
        el: '.page',
        render: function(){

            var users = new Users();
            users.fetch({
                success: function() {
                    console.log('success');

                }
            })
                this.$el.html('test');

        }
    });

But when I insert the this.$el.html('test'); into the success callback I am getting an error :

TypeError: 'undefined' is not an object (evaluating 'this.$el.html')

var UserList = Backbone.View.extend({
        el: '.page',
        render: function(){

            var users = new Users();
            users.fetch({
                success: function() {
                    console.log('success');
                    this.$el.html('test');
                }
            })
        }
    });

The console log is fired correctly.


Solution

  • Inside success the context has changed, so this no longer refers to the view object (it actually refers to the JQuery Ajax object, I believe). To work around this you can save a reference to the view using var self = this:

    var users = new Users();
    var self = this;
    users.fetch({
        success: function() {
            console.log('success');
            self.$el.html('test');
        }
    })