如何通过Ajax在Backbone View中缓存jQuery模板?

时间:2011-11-18 17:32:51

标签: backbone.js jquery-templates

我正在使用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调用之后不再为null,但即使设置它是回调的一部分,它也是未定义的。因此,即使#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
    ...

2 个答案:

答案 0 :(得分:1)

我最好的猜测是$ .get中的this.template超出了范围。

您可能想要

initialize:
var self = this;
//this.template is null at this point

     if(!($.isFunction(self.template))){
        $.get('template/file.html', function(templates){
            $('body').append(templates);
            self.template = $('#templateElement').template();
        });
}

答案 1 :(得分:1)

右。您已经丢失了'this',这不是您在$ .get()调用中的视图。 您可以使用underscore.bind在视图的上下文中调用成功回调。

但是,您实际上并不需要将模板放入DOM中。

您可以在View原型上设置已编译的模板,它将用于此视图的下一个实例。例如,像......

BbView = Backbone.View.extend({

  initialize: function() {
    if(!($.isFunction(this.template))) {
      $.get('template/file.html', _.bind(function(templates) {
        BbView.prototype.template = $(templates).template();
      }), this);
    }
    // Now you have this.template, for this and all subsequent instances
  }