2012-05-30 26 views
2

我試圖按照http://ricostacruz.com/backbone-patterns/#inline_templates避免http://ricostacruz.com/backbone-patterns/#abuse但我有這樣一個典型的觀點:如果app.js文件沒有準備好,如何使用this.template?

// in app.js 
App.MyView = Backbone.View.extend({ 
    className: "ui-widget-content", 
    template: _.template($("#myTemplate").html()), 
    render: function() 
    { 
     this.$el.html(this.template(this.model.toJSON())); 
    } 

然後我有這樣的

<script src="./js/jquery-1.7.2.min.js"></script> 
<script src="./js/jquery-ui-1.8.20.custom.min.js"></script> 
<script src="./js/underscore.js"></script> 
<script src="./js/backbone.js"></script> 
<script src="./js/app.js"></script> 

瀏覽器app.js抱怨說,$("#myTemplate")線的應用.MyView.template是null(因爲文檔沒有準備好?)。我該怎麼辦?

回答

1

我快速修復,這是編譯在視圖初始化模板..

App.MyView = Backbone.View.extend({ 
    className: "ui-widget-content", 
    template: '#myTemplate', 
    initialize: function(){ 
     this.template = _.template($(this.template).html()); 
    }, 
    render: function(){ 
     this.$el.html(this.template(this.model.toJSON())); 
    } 

那麼一切還是以同樣的,你可以把你的渲染方法在基類..

0

做的僅僅是不緩存模板的最簡單的事情:

App.MyView = Backbone.View.extend({ 
    className: "ui-widget-content", 
    render: function() 
    { 
     var template = _.template($("#myTemplate").html()) 
     this.$el.html(template(this.model.toJSON())); 
    } 
+0

是,那會是最簡單的,但我認爲下劃線'編譯'代價昂貴,應該緩存? – Henry

+0

視圖的上下文是什麼?它每頁翻譯數百次還是一次? – asawyer

+0

小於幾百。 – Henry

2

爲什麼不懶加載你的模板?首次使用時編譯模板,並將編譯後的模板緩存在視圖的「類」中。你甚至可以添加你的基本觀點來處理這個緩存像這樣的東西:

var BV = Backbone.View.extend({ 
    template: function(data) { 
     if(!this.constructor.prototype._template) 
      this.constructor.prototype._template = _.template($('#' + this.tmpl_id).html()); 
     return this._template(data); 
    } 
}); 

然後你可以有這樣的事情:

var V = BV.extend({ 
    tmpl_id: 'tmpl', 
    render: function() { 
     this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    } 
}); 

#tmpl模板會被編譯第一次,它是使用,它將被編譯至多一次。

演示:http://jsfiddle.net/ambiguous/hrnqC/

通知的沒有包(頭)的演示,並看看控制檯查看被編譯的時間和頻率。

相關問題