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