TIMEX
TIMEX

Reputation: 271704

How do I use "this" in my Backbone View?

var homeView = Backbone.View.extend({
        el:  $("#main_container"),
        initialize: function(){
            _.bindAll(this, 'render');
        },
        render:function(){
            $.get('/home', {}, function(data){
                console.log(data);
                var tpl = _.template(home_container_temp, {});
                this.el.html(tpl);
            });
        }
    });

I want to do a ajax GET request, and then set the data. But I can't do it because I get:

Uncaught TypeError: Cannot call method 'html' of undefined

Upvotes: 0

Views: 665

Answers (2)

Jeffrey Zhao
Jeffrey Zhao

Reputation: 5023

That's the JavaScript feature of "dynamic this", if you want to use "this" in your callback, please keep it in the variable outside the callback:

render: function() {
    var _this = this; // keep it outside the callback
    $.get('/home', {}, function(data){
        console.log(data);
        var tpl = _.template(home_container_temp, {});
        // use the _this variable in the callback.
        _this.el.html(tpl);
    });
}

Upvotes: 0

kubetz
kubetz

Reputation: 8556

this inside the $.get() is not refering to the view.

Try:

var homeView = Backbone.View.extend({
    el:  $("#main_container"),
    initialize: function(){
        _.bindAll(this, 'render');
    },
    render:function(){
        var $el = this.el;
        $.get('/home', {}, function(data){
            console.log(data);
            var tpl = _.template(home_container_temp, {});
            $el.html(tpl);
        });
    }
});

Upvotes: 4

Related Questions