2012-06-22 89 views
0

下面的行完全失敗。帶有Backbone.js錯誤的Underscore.js模板

template: _.template($('#test').html()), 

試圖跟隨從https://github.com/ccoenraets/backbone-jquerymobile一個簡單的例子使用jQuery移動與沿Backbone.js的。我在Web檢查器中得到的錯誤是:TypeError:'null'不是一個對象(評估'str.replace'),它位於underscore.js的第913行。使用的是_.template這種方式:

template: _.template("<h1>To Do</h1>"), 

的作品,但爲了融入jQuery手機風格,這種方式不會這樣做。

todo.js

TodoBb.Views.ComCentersTodo = Backbone.View.extend({ 

template: _.template($('#test').html()), 


render: function() { 
    $(this.el).html(this.template()); 
    return this; 
} 
}); 

main.html中

<script type = 'text/template' id = 'test'> <h1>To Do</h1> </script> 
+0

那麼最新的問題? jQuery移動樣式不顯示?爲此,您需要觸發創建事件,如$(「...」)。trigger(「create」)',現在只需查看文檔,我無法找到創建事件 – jm2

回答

2

當你的視圖被解析DOM是沒有準備好:

TodoBb.Views.ComCentersTodo = Backbone.View.extend({ 
    template: _.template($('#test').html()), 
    //... 
}); 

所以$('#test').html()null和你實際上是這樣做的:

TodoBb.Views.ComCentersTodo = Backbone.View.extend({ 
    template: _.template(null), 
    //... 
}); 

_.template的內部使用replace,同時將模板轉換爲JavaScript函數。

您有幾種選擇:

  1. TodoBd.Views.ComCentersTodo定義一個$(document).ready()處理器中:

    $(function() { 
        TodoBb.Views.ComCentersTodo = Backbone.View.extend({ 
         template: _.template($('#test').html()), 
         //... 
        }); 
    }); 
    
  2. ,直到你需要它不要編譯模板:

    TodoBb.Views.ComCentersTodo = Backbone.View.extend({ 
        //... no template in here 
        render: function() { 
         var html = _.template($('#test').html(), this.model.toJSON()); 
         this.$el.html(html); 
         return this; 
        }, 
        //... 
    }); 
    

作爲的變體,您可以在某處緩存已編譯的模板函數,並且只有在您第一次使用它時纔會調用_.template($('#test').html())