0
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

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

THanks. Why the dollar sign in front of the var $el? Why not leave the dollar sign out?
@TIMEX The $el is just my preference to indicate that the variable contains a jQuery object. It has no functional consequences. You can name the variable however you want.
0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.