我正在使用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
...
在這種情況下,綁定不是必需的,因爲'this'沒有被使用,但至少你可以看到它是如何工作的。 – maxl0rd
謝謝。我不知道下劃線的方法,但我看到你如何使用View.prototype.template來緩存模板。我沒有執行此修復程序,但會在我獲得時間時執行此修復程序。 – tim