2011-11-18 61 views
0

我正在使用backbone.js和jQuery模板。我想要做的是將視圖的模板設置爲dom元素。它看起來像這樣:如何通過Ajax在主幹視圖中緩存jQuery模板?

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

回答

1

權。您在調用$ .get()時失去了「this」,這不是您的觀點。 您可以使用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 
    } 
+0

在這種情況下,綁定不是必需的,因爲'this'沒有被使用,但至少你可以看到它是如何工作的。 – maxl0rd

+0

謝謝。我不知道下劃線的方法,但我看到你如何使用View.prototype.template來緩存模板。我沒有執行此修復程序,但會在我獲得時間時執行此修復程序。 – tim

1

我最好的猜測是,$不用彷徨裏面你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(); 
     }); 
} 
+0

謝謝 - 你是對的,這是超出範圍。然而,設置自己似乎沒有幫助。你確實指出我在正確的方向:) – tim

+0

好的交易,你怎麼解決它? – jcreamer898

+0

我將$ .get直接放入事件處理程序中,然後實例化視圖。那是作弊嗎?我將嘗試下面的方法... – tim