【发布时间】:2012-01-01 10:57:21
【问题描述】:
我正在使用backbone.js 和jQuery 模板。我想做的是将视图的模板设置为 dom 元素。它看起来像这样:
<script id="templateElement" type="text/x-jQuery-tmpl">
<div class='foo'>bar</div>
</script>
视图初始化的时候,会用$.isFunction查看模板是否存在。如果不是,它将从外部文件中获取它并将返回的 dom 元素附加到 body 元素,然后将 this.template 设置为该 dom 元素。
下次调用视图时,该 dom 元素应该存在,因此没有理由再次发出 AJAX 调用。但是,我发现虽然这个模板在 AJAX 调用后不再为空,但它是未定义的,即使设置它是回调的一部分。因此,即使#templateElement 是页面的一部分,每次呈现视图时都会发出我的 AJAX 调用。
发生了什么事?
BbView = Backbone.View.extend({
template: $('#templateElement').template(),
initialize:
//this.template is null at this point
if(!($.isFunction(this.template))){
$.get('template/file.html', function(templates){
$('body').append(templates);
this.template = $('#templateElement').template();
});
}
//this.template is undefined at this point
...
【问题讨论】:
标签: backbone.js jquery-templates