如何使用RequireJS的Handlebars

时间:2017-04-06 14:00:34

标签: 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;
});

1 个答案:

答案 0 :(得分:0)

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