2013-02-18 40 views
0
define([ 
    'jquery', 
    'underscore', 
    'backbone', 
    'text!modules/index/templates/container.html' 
], function($, _, Backbone, container_temp){ 
    var indexView = Backbone.View.extend({ 
     el: $('.main_container'), 
     initialize:function(){ 
      _.bindAll(this, 'render'); 
     }, 
     render:function(){ 
      var $this = this; 
      var $el = this.el; 
      $.get('/js/index/render', {}, function(data){ 
       var dat = JSON.parse(data); 
       $this.pars = dat; 
       var tpl = _.template(container_temp, dat); 
       $el.html(tpl); 
      }); 
     } 
    }); 
    return new indexView; 
}); 

運行此代碼應該用HTML填充$ el。但是,我的瀏覽器在$el.html(tpl);處出現混亂。爲什麼我的「el」不能在Backbone中工作?

Uncaught TypeError: Object #<HTMLDivElement> has no method 'html' 

爲了解決這個問題,我必須這樣做:$($el).html(tpl);讓jQuery的寄存器。

這看起來很尷尬。在我過去的項目中,我一直以前的方式完成它,並且一直都很成功。

+1

在'GET'回調,只要使用'$此$ el'和刪除本地'$。 el' =>'$ this。$ el.html(tpl)'。你已經通過在'$ this'變量中捕獲它來創建'this'的閉包,所以你可以直接使用它(因爲你不會多次使用它,它不會節省任何時間)。 – WiredPrairie 2013-02-18 14:14:55

回答

3

this.el是一個原始DOM元素,但html方法屬於jQuery。

嘗試var $el = this.$el;在渲染方法:

render:function(){ 
    var $this = this; 
    var $el = this.$el; 
    $.get('/js/index/render', {}, function(data){ 
     var dat = JSON.parse(data); 
     $this.pars = dat; 
     var tpl = _.template(container_temp, dat); 
     $el.html(tpl); 
    }); 
} 
2

如果你看一下你的渲染功能:

render:function(){ 
     var $this = this; 
     var $el = this.el; 
     $.get('/js/index/render', {}, function(data){ 
      var dat = JSON.parse(data); 
      $this.pars = dat; 
      var tpl = _.template(container_temp, dat); 
      $el.html(tpl); 
     }); 
    } 

您明確分配var $el所以下面$ EL等於this.el這是原始沒有jQuery包裝的dom元素,你通常用$ el獲得。

試試這個:this.$el沒有var declaration

因此獲得$ EL到$不用彷徨範圍的代碼是這樣:

render:function(){ 
    var $this = this; 
    var element = this.$el; 
    $.get('/js/index/render', {}, function(data){ 
     var dat = JSON.parse(data); 
     $this.pars = dat; 
     var tpl = _.template(container_temp, dat); 
     element.html(tpl); 
    }); 
} 
相關問題