javascript - 如何将 Handlebars 与 RequireJS 一起使用

标签 javascript requirejs handlebars.js

我遇到了以下错误:

Uncaught TypeError: Cannot call method 'compile' of undefined.

RequireJS 配置:

requirejs.config({
    baseUrl: "resources",
    paths: {
        'app':'lib',
        'jquery': 'lib/jquery-1.9.1',
        'bootstrap': 'lib/bootstrap',
        'html5shiv': 'lib/html5shiv',
        'spin': 'lib/spin',
        'respond': 'lib/respond',
        'underscore': 'lib/underscore',
        'backbone': 'lib/backbone',
        'handlebars': 'lib/handlebars-v3.0.3',
        'template': 'app/templates'
    },
    shim: {
        html5shiv: {
            deps: ['jquery']
        },
        respond: {
            deps: ['jquery']
        },
        bootstrap: {
            deps: ['jquery']
        },
        jquery: {
            exports: '$'
        },
        underscore: {
            exports: '_'
        },
        backbone: {
            deps: ['jquery', 'underscore'],
            exports: 'Backbone'
        },
        handlebars: {
            exports: "Handlebars"
        }
    }
});

require([
    'jquery',
    'underscore',
    'backbone',
    'handlebars',
    'app/Router'
], function($,
            _,
            Backbone,
            Handlebars,
            Router) {
    var router = new Router();
    Backbone.history.start();
});

查看:

define([
  'backbone',
  'handlebars',
  'text!templates/mytemplate.html'
], function(Backbone, Handlebars, Template){

    MyView = Backbone.View.extend({
        tagName: 'li',
        template: Handlebars.compile(Template),

        render: function() {
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }
    });

    return MyView;
});

最佳答案

shim 适用于不支持 AMD 的库。您使用的 Handlebars 版本可能支持 AMD,并且没有定义名为 Handlebars 的全局变量。因此你会得到错误。尝试从 shim 中删除 handlebars 配置。

关于javascript - 如何将 Handlebars 与 RequireJS 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43257467/

相关文章:

requirejs - 如何在Aurelia-CLI中添加系绳以与Bootstrap 4一起使用

node.js - 在 Require.js 优化器中打包 *.html 模板?

javascript - 无法提供模板

meteor - 铁路由器和 meteor : Template rendering on different url

javascript - Winston 添加自定义日志级别

javascript - 如何在 Windows 应用商店应用中加载 CDN JS 文件?

internationalization - 如何使用 r.js 和 hbs.js 使用多个语言环境

javascript - Node.js - 无法使用 $(this) 从 jquery 到达 Handlebars 元素

javascript - 当条件肯定为真时,Javascript < 运算符返回 false 的问题

javascript - 日历时间表