2013-05-20 45 views
0

目前,我正在學習Backbone.js的,還是在最開始,但我得到的錯誤:Backbone.js的EL錯誤

Uncaught TypeError: Cannot call method 'html' of undefined 

上線此$ el.html(模板) ;

<body> 
       <div id="search_container"></div> 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
       <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script> 
       <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script> 
       <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script> 
       <script type="text/template" id="search_template"> 
         <label>Search</label> 
         <input type="text" id="search_input" /> 
         <input type="button" id="search_button" value="Search" /> 
       </script> 
       <script type="text/javascript"> 
         $(document).ready(function() 
         { 

           SearchView = Backbone.View.extend({ 
           initialize: function(){ 
             this.render(); 
           }, 
           render: function(){ 
             // Compile the template using underscore 
             var template = _.template($("#search_template").html(), {}); 
             // Load the compiled HTML into the Backbone "el" 
             this.$el.html(template); 
           } 
           }); 

           var search_view = new SearchView({ el: $("#search_container") }); 
         }); 
       </script> 
     </body> 

爲什麼這個錯誤出現?

+0

嘗試在所有腳本之前將div放在身體標記的頂部。我認爲你的JavaScript在div存在之前正在執行。 –

+0

沒有相同的錯誤:( – Noor

+1

你真的應該使用最新版本的骨幹,0.3.3是從石器時代。 –

回答

-1

當您在JavaScript代碼中引用DOM元素時,該元素必須已經可用 - 應在創建此元素後運行JS代碼。這裏,#search_container div指向視圖的el字段是在腳本執行後創建的。爲了避免這樣的問題,使用jQuery的ready方法:

$(document).ready(function() 
{ 
    SearchView = Backbone.View.extend({ 

     // ... 

    }); 

    // ... 
}); 

此方法運行創建HTML文檔後,作爲參數傳遞的功能,所有的元素都可以使用。

另外,您使用的骨幹版本似乎不會自動管理$el屬性的值。如果您需要使用這個版本更新initialize方法是這樣的:

initialize: function() 
{         
    this.$el = $(this.el); 
    this.render(); 
}, 

這將手動設置$el爲需要的值。

+0

nopes,同樣的問題,我用你的建議編輯了這個問題 – Noor

+0

更新'underscore'和'backbone'到最近的版本,你可以在http://backbonejs.org/和http://underscorejs.org/找到這些文件。 – mirrormx

1

你的觀點的EL元件設置爲

new SearchView({ el: $("#search_container") }); 

但無處在你的HTML是元素已經存在。這個錯誤的原因, 這樣定義el就意味着你已經在該頁面上出現了該元素,並將該元素指定爲該視圖的容器。

要麼元素添加到HTML或編輯它像下面

new SearchView(); 

使得el將默認回落到一個div。