加载外部下划线模板

Load external underscore template

本文关键字:下划线 外部 加载      更新时间:2023-09-26

我在主干应用程序中加载外部下划线模板时遇到了麻烦。内联模板(注释掉了)工作得很好,但是外部模板不行。

$.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'

我猜它与我的应用程序在一个函数内,但我不确定如何解决这个问题。

在你调用$('#tpl_observation_summary').html()的那一刻,DOM似乎还没有准备好,你得到null作为_.template的第一个参数,从而导致下划线不能处理一个不是字符串的字符串。

则不能定义bootstrap方法,因此不能作为$.app的函数调用。

模板初始化可以包含在Backbone视图的第一个initialize调用中。