2013-04-15 63 views
1

我在加載外部下劃線模板時遇到了問題。內聯模板(註釋掉)工作得很好,但外部不行。加載外部下劃線模板

$.app.ObservationSummaryView = Backbone.View.extend({ 
    tagName: 'div', 
    className: 'observation_summary_view', 
    // template: _.template('ID: <%= id %><p>Comments:<%= comments.length %>'), 
    template: _.template($('#tpl_observation_summary').html()), 
    initialize: function(){ 
     _.bindAll(this, 'render', 'on_click'); 
     this.model.bind('change', this.render); 
    }, 
    render: function(){ 
     return $(this.el).html(this.template(this.model.toJSON())); 
    }, 
    on_click: function(e){ 
     $.app.app.navigate('observation/' + this.model.get('id') + '/', {trigger: true}); 
    } 
}); 

HTML /模板:

<script type="text/template" id="tpl_observation_summary"> 
<%= id %> 
</script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
    (function($) { 
    $.app.bootstrap(); 
})(jQuery); 
}); 
</script> 

錯誤:

Uncaught TypeError: Cannot call method 'replace' of undefined underscore.js:1131 
Uncaught TypeError: Object #<Object> has no method 'bootstrap' 

我猜它做的東西跟我的應用程序在函數內部是,但我不知道如何解決這個問題。

+0

DOM準備好了模板編譯時間嗎?我認爲這並不考慮你如何稱主要方法。 – lib3d

+0

新增,相同的結果:(。 – ObviousCat

+1

我的意思是ObservationSummaryView中的編譯:$(...)。html()被稱爲太早,可能會失敗 – lib3d

回答

1

在你打電話$('#tpl_observation_summary').html()的那一刻,DOM似乎還沒有準備好,你會得到null作爲_.template第一個參數,從而導致underscoreJS不能夠有一個字符串,它不是一個工作。

然後bootstrap方法不能被定義,因此不能作爲$.app函數被調用。

模板初始化可以包含在您的Backbone視圖的第一個initialize調用中。