2011-05-16 44 views
1

這裏做一個觀點我想在Backbone.js的錯誤到來而在Backbone.js的

// The DOM element for a User item... 
    var UserView = Backbone.View.extend({ 
     //... is a list tag. 
     tagName: "li", 
     // Cache the template function for a single item. 
     template: _.template($('#tmpl_occupant').html()), 

     // a one-to-one correspondence between a **User** and a **UserView** in this 
     // app, we set a direct reference on the model for convenience. 
     initialize: function() { 

      _.bindAll(this, 'render', 'close'); 
      this.model.bind('change', this.render); 
      this.model.view = this; 
     }, 
     // Re-render the contents of the User item. 
     render: function() { 
      $(this.el).html(this.template(this.model.toJSON())); 
      return this; 
     } 
    }); 

這種看法代碼,我把在user.js的視圖,並在index.html的加載它被稱爲它給錯誤

str is null 
http://myserver/rahul/js/underscore-1.1.3.js 
Line 675 

我認爲這是由於因錯誤不來,當我刪除此行

template: _.template($('#tmpl_occupant').html()), 


<script type="text/html" id="tmpl_occupant"> 
    <%=user.username%> is in <%=gib.name%> (<%=channel%>) 
    </script> 

我認爲這是因爲index.html沒有完全加載,而這行是執行.so它不好tmpl_occupant,我可以做什麼來解決這個問題。

回答

0

通過直接傳遞字符串而不是jquery引用完成它。 或

http://documentcloud.github.com/underscore/#template 更好的解決方案是編譯模板並將模板傳遞給視圖實例。

+1

我沒說得對。我怎麼能傳遞一個字符串,而不是jQuery的參考?我也用我的代碼模板:_.template($(「tpl-item-list」)。html()), – jongbanaag 2012-03-23 02:39:26

+0

opps。現在明白了。謝謝 :) – jongbanaag 2012-03-23 02:41:36

3

我該怎麼辦才能解決這個問題?

首先,您可以將初始化腳本移動到HTML文檔的底部。這可以確保在加載所有HTML後運行它。

否則,您可以將您的初始化代碼包裝在$(document).ready()塊中,這將確保文檔已完全加載並且HTML可用。我的代碼看起來是這樣的:

ApplicationController = Backbone.Controller.extend({ 
    /* router code here */ 
}); 

$(document).ready(function() { 
    myapp = new ApplicationController() 
}); 

這使用jQuery的DOM準備的事件,以確保一切正在運行的客戶端代碼的第一行前準備好。

+0

您還必須在初始化函數中初始化模板。 – Julien 2011-05-17 02:23:24

+0

Julien:爲什麼? Rahul正在使用underscore.js模板;除了被拉出DOM到HTML字符串之外,他們不需要進行很多初始化。如果模板嵌入到文檔中,就像我經常使用腳本標記一樣,那麼當DOM樹處於活動狀態時它就會出現。 – 2011-05-17 14:21:43

+1

他的模板屬性正在查看DOM以加載模板。 – Julien 2011-05-17 15:32:26