2011-12-04 28 views
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); 
      }); 
     } 
    }); 

我想做一個ajax GET請求,然後設置數據。但我不能這樣做,因爲我得到:如何在我的骨幹視圖中使用「this」?

Uncaught TypeError: Cannot call method 'html' of undefined 

回答

4

this$.get()內不指的視圖。

嘗試:

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); 
     }); 
    } 
}); 
+0

謝謝。爲什麼美元在var $ el前面簽字?爲什麼不讓美元退出? – TIMEX

+0

@TIMEX'$ el'只是我的首選項,表明變量包含一個jQuery對象。它沒有功能性後果。不管你想要什麼,你都可以命名變量。 – kubetz

0

這就是「動態this」 JavaScript的功能,如果你想用「這個」,在你的回調,請保持在回調外的變量:

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); 
    }); 
}