Javascript 车把误差

Javascript 车把误差,javascript,handlebars.js,Javascript,Handlebars.js,我已经设置了把手,它运行得很好,但是当我包含我的“add”方法并尝试运行render方法时,它会抛出一个错误: “您必须将字符串或Handlebars AST传递给Handlebars.compile。您传递的是未定义的” 不太清楚为什么 HTML 在init函数中调用this.render() render函数包含以下行: this.toDoTemplate = Handlebars.compile(this.toDoTemplate.innerHTML); 因此,在初始化this.toDo

我已经设置了把手,它运行得很好,但是当我包含我的“add”方法并尝试运行render方法时,它会抛出一个错误:

“您必须将字符串或Handlebars AST传递给Handlebars.compile。您传递的是未定义的”

不太清楚为什么

HTML


init
函数中调用
this.render()

render
函数包含以下行:

this.toDoTemplate = Handlebars.compile(this.toDoTemplate.innerHTML);
因此,在初始化
this.toDoTemplate
之后,它将保存对已编译模板的引用,而不是
script
元素

在您的
add
中,您再次调用
render
,但由于这次
this.toDoTemplate
保存了已编译的模板,因此
this.toDoTemplate.innerHTML将
未定义
,而不是字符串,您将得到错误:

必须向handlebar.compile传递字符串或handlebar AST。你未定义地通过了考试

如何解决这个问题取决于用例

解决方法之一是在
缓存dom
中编译模板:

 this.toDoTemplate = Handlebars.compile(document.getElementById('to-do-template'));
另一种方法是使用两个属性:

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

每次调用
render
时编译模板很可能是您无论如何都不想做的事情

 this.toDoTemplate = Handlebars.compile(document.getElementById('to-do-template'));
 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);
 }