【问题标题】:Load external underscore template加载外部下划线模板
【发布时间】:2013-04-16 04:34:55
【问题描述】:

我在我的主干应用程序中加载外部下划线模板时遇到问题。内联模板(已注释掉)可以正常工作,但外部不能。

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

我猜这与我的应用在函数中有关,但我不确定如何解决。

【问题讨论】:

  • 模板编译时 DOM 准备好了吗?我认为它没有考虑你如何调用 main 方法。
  • 已添加,结果相同 :(.
  • 我的意思是 ObservationSummaryView 中的编译:$(...).html() 调用得太早,可能会失败
  • 我会被诅咒的......谢谢。我想这就是 20 小时的编码马拉松将产生的结果。将其发布为答案,以便我给你信用:=)。

标签: javascript backbone.js underscore.js


【解决方案1】:

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

那么bootstrap方法不能被定义,所以不能作为$.app的函数调用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    相关资源
    最近更新 更多