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
asked Dec 4, 2011 at 3:21
TIMEX
275k369 gold badges805 silver badges1.1k bronze badges
2 Answers 2
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);
});
}
});
answered Dec 4, 2011 at 3:31
kubetz
8,5661 gold badge25 silver badges27 bronze badges
Sign up to request clarification or add additional context in comments.
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);
});
}
answered Dec 4, 2011 at 5:23
Jeffrey Zhao
5,0434 gold badges32 silver badges53 bronze badges
Comments
default