我在骨干应用程序中加载外部下划线模板时遇到问题。内联模板(注释掉)工作得很好,但外部没有。
$.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 :(得分:1)
当你调用$('#tpl_observation_summary').html()
时,DOM似乎没有准备就绪,你得null
作为_.template
的第一个参数,从而导致下划线无法使用一个不是一个字符串。
然后无法定义bootstrap
方法,因此不能将其作为$.app
的函数调用。
模板初始化可以包含在Backbone视图的第一个initialize
调用中。