【问题标题】:How To Cache jQuery Template In Backbone View via Ajax?如何通过 Ajax 在主干视图中缓存 jQuery 模板?
【发布时间】: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


    【解决方案1】:

    没错。在调用 $.get() 时,您丢失了“this”,这不是您的视图。 您可以使用 underscore.bind 在您的视图上下文中调用成功回调。

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

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

    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
      }
    

    【讨论】:

    • 在这种情况下,绑定不是必需的,因为没有使用'this',但至少你可以看到它是如何工作的。
    • 谢谢。我对下划线的方法一无所知,但我知道您如何使用 View.prototype.template 来缓存模板。我还没有实现这个修复,但是当我有时间的时候。
    【解决方案2】:

    我最好的猜测是 $.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();
            });
    }
    

    【讨论】:

    • 谢谢 - 你说得对,这超出了范围。但是,将 self 设置为此似乎无济于事。不过,您确实为我指明了正确的方向:)
    • 不错,你是怎么解决的?
    • 在实例化视图之前,我将 $.get 直接放在事件处理程序中。这是作弊吗?我要试试下面的方法……
    猜你喜欢
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    相关资源
    最近更新 更多