车把编译错误

Pau*_*aul 0 javascript backbone.js handlebars.js

嗨,我一直在尝试使用backbonejs和handlebar模板,但似乎我的jSON是错误的或数据没有正确解析.入门

Uncaught Error: You must pass a string to Handlebars.compile. You passed undefined
Run Code Online (Sandbox Code Playgroud)

代码可以在

的jsfiddle

任何建议将被认真考虑

mu *_*ort 6

你的小提琴以各种方式被打破,但你可能会这样做:

template: Handlebars.compile($('#tpl-page-list-item').html()),
Run Code Online (Sandbox Code Playgroud)

在有#tpl-page-list-item可用之前.如果您的页面如下所示,则会发生这种情

<script src="your_backbone_javascript.js"></script>
<script id="tpl-page-list-item" ...></script>
Run Code Online (Sandbox Code Playgroud)

因为您的Backbone视图将在<script id="tpl-page-list-item">添加到DOM 之前被解析.您可以将Backbone视图包装在文档就绪处理程序中(使用适当的命名空间来考虑函数包装器):

$(function() {
    window.PageListItemView = Backbone.View.extend({
        template: Handlebars.compile($('#tpl-page-list-item').html()),
        //...
    });
});
Run Code Online (Sandbox Code Playgroud)

或在实例化视图时编译模板:

initialize: function() {
    // Or check if it is in the prototype and put the compiled template
    // in the prototype if you're using the view multiple times...
    this.template = Handlebars.compile($('#tpl-page-list-item').html());
    //...
}
Run Code Online (Sandbox Code Playgroud)