2017-08-05 2 views
2

Handlebars.compileは。あなたは合格ハンドルエラー

すぎてわからない「未定義なぜ...

HTML

<div id="to-do-app"></div> 
<input id="add-to-do-value" type="text" placeholder="Add to do"> 
<button id="add-to-do">Add</button> 
<script type="text/javascript" src="js/handlebars.js"></script> 
<script id="to-do-template" type="text/template"> 
    <ul> 
     {{#this}} 
     <div> 
      <li>{{value}}</li> 
     </div> 
     {{/this}} 
    </ul> 
</script> 
<script type="text/javascript" src="js/app.js"></script> 

JS

(function() { 
    var toDo = { 
     data: [], 
     cacheDom: function() { 
      this.toDoApp = document.getElementById('to-do-app'); 
      this.toDoTemplate = document.getElementById('to-do-template'); 
      this.addToDo = document.getElementById('add-to-do'); 
      this.addToDoValue = document.getElementById('add-to-do-value'); 
     }, 
     render: function() { 
      this.toDoTemplate = Handlebars.compile(this.toDoTemplate.innerHTML); 
      this.toDoApp.innerHTML = this.toDoTemplate(this.data); 
     }, 
     bindEvents: function() { 
      this.addToDo.addEventListener("click", this.add.bind(this)); 
     }, 
     add: function() { 
      var toDoValue = this.addToDoValue.value; 
      if(toDoValue) { 
       var toDoObj = { 
        value: toDoValue 
       } 
      this.data.push(toDoObj); 
      } 
      this.render(); 
     }, 
     init: function() { 
      this.cacheDom(); 
      this.bindEvents(); 
      this.render(); 
     } 
    } 

    toDo.init(); 
})(); 

答えて

1

init関数では、this.render()と呼びます。あなたはthis.toDoTemplateがコンパイルテンプレートではなくscript要素への参照を保持しますinitの後にそう

this.toDoTemplate = Handlebars.compile(this.toDoTemplate.innerHTML); 

render関数は、この行が含まれています。

You must pass a string or Handlebars AST to Handlebars.compile. You passed undefined

あなたがこの問題を解決する方法によって異なります。あなたは再びrenderを呼び出すが、今回this.toDoTemplatethis.toDoTemplate.innerHTMLundefinedではなく、文字列、あなたはエラーになりますこれらのだろうコンパイルしたテンプレートが保持しているためaddあなたに

ユースケースでソリューションに

はあなたのcacheDomでテンプレートをコンパイルするために、次のようになります。テンプレートのコンパイル

this.toDoTemplateElement = document.getElementById('to-do-template') 

そして

if(!this.toDoTemplate) { // only compile it once and cache the compiled template 
    this.toDoTemplate = Handlebars.compile(this.toDoTemplateElement.innerHTML); 
} 

this.toDoTemplate = Handlebars.compile(document.getElementById('to-do-template')); 

もう一つは、2つのプロパティを使用することですあなたが電話するたびにrenderがそうする可能性が最も高いとにかくやりたくない。

関連する問題