2011-12-04 19 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リクエストを行い、データを設定したいと考えています。 $.get()内部バックボーンビューで「this」を使用するにはどうすればよいですか?

Uncaught TypeError: Cannot call method 'html' of undefined 

答えて

4

thisは、ビューに参照のうえされていない:私は得るので、しかし、私はそれを行うことはできません。

試してみてください。

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

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