车把编译错误

时间:2013-11-07 19:34:17

标签: javascript backbone.js handlebars.js

您好我一直在尝试使用backbonejs和handlebar模板,但似乎我的jSON错误或数据未正确解析。获得

Uncaught Error: You must pass a string to Handlebars.compile. You passed undefined

代码可以在

找到

jsfiddle

任何建议都将受到赞赏

1 个答案:

答案 0 :(得分:6)

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

template: Handlebars.compile($('#tpl-page-list-item').html()),

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

<script src="your_backbone_javascript.js"></script>
<script id="tpl-page-list-item" ...></script>

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

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

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

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());
    //...
}