2013-03-27 85 views
5

「取代」在我的骨幹觀點,我有:UnderscoreJS遺漏的類型錯誤:無法調用未定義

noteTemplate: _.template($('#note-template').html()),

這是引發此錯誤。模板是:

<script type="text/template" id="note-template"> 
    <div class="reminder"> 
     <div class="reminder-hover"> 
      <div class="title"><%= title %></div> 
      <div class="created">Created 3 days ago <span class="pull-right"> In 3 hours</span></div> 
     </div> 
     <span class="id" style="display: none;"><%= id %></span> 
    </div> 
</script> 

我很困惑,因爲這部作品在我的控制檯:

>> _.template($('#note-template').html());
function (n){return e.call(this,n,w)}

下面是完整的代碼:

App.Views.Index = Backbone.View.extend({ 

    el: $("div.reminders"), 
    todays : $("span.today"), 
    tomorrows : $("span.tomorrow"), 
    weeks : $("span.week"), 
    all_times : $("span.all-time"), 

    noteTemplate: _.template($('#note-template').html()), 


    events: { 
     "click .reminder" : "editNote", 
     "click .newNote" : "newNote" 
    }, 

    initialize : function() { 
     _.bindAll(this, 'render'); 
     this.notes = this.options.notes; 
     this.listenTo(this.model, 'change', this.render); 
    }, 

    render : function() { 
     // Hide things related to editing a note 
     this.$("[name=content]").hide().val(""); 
     this.$("[name=title]").hide().val(""); 
     this.$("save1").hide(); 
     this.$("close1").hide(); 

     // Fill in content 
     this.$el.html(this.noteTemplate(this.model.toJSON())); 
     this.$todays.html(collection.getTodays.length); 
     this.$tomorrows.html(collection.getTomorrows.length); 
     this.$weeks.html(collection.getWeeks.length); 
     this.$all_times.html(collection.getAllTimes.length); 
     return this; 
    }, 

    editNote : function() { 
     this.goTo("notes/"+this.model.id); 
    }, 

    newNote : function(){ 
     this.goTo("newNote"); 
    } 

}); 

回答

16

而不是試圖要在定義方法時緩存備註模板HTML,請在初始化視圖時執行此操作。

initialize : function() { 
    // ... 
    this.nodeTemplate = _.template($('#note-template').html()); 
} 

這很可能是您在DOM(因此模板)加載之前定義視圖。

+0

完全忘了。謝謝! – Nonconformist 2013-03-27 02:00:21

2

另一種解決方案是移動上面的調用視圖的標籤劇本,像這樣(我用玉)

script#page-thumb(type='text/template') 
    .page-thumb-container.relative 
     .page-thumb 
     .image 
      figure 
      img(src='{{ image }}' , width='80px',height='60px' , data-id='{{ id }}') 
      span.title {{ title }} 
     .page-dragger.absolute 

script(src='js/src/views/PageThumbView.js') 
相關問題