我正在建立一个Backbone
项目,Handlebars
但我遇到了Handlebars
找不到编译方法的问题。这是我的配置文件:
require.config({
hbs: {
templateExtension: '.hbs'
},
paths: {
backbone: "libs/backbone/backbone",
handlebars: 'libs/handlebars/handlebars.amd',
hbs: 'libs/requirejs-hbs/hbs',
jquery: 'libs/jquery/jquery',
jqueryMockAjax: 'libs/jquery-mockjax/jquery.mockjax',
text: 'libs/requirejs-text/text',
templates: 'templates/',
underscore: 'libs/underscore/underscore'
},
shim: {
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
hbs: {
deps: ['handlebars'],
exports: 'hbs'
},
jqueryMockAjax: {
deps: [ 'jquery' ],
exports: '$.mockjax'
},
underscore: {
exports: '_'
}
}
});
require(['app'], function(App) {
'use strict';
var app = new App();
app.render();
});
这是app.js
我要渲染的:
define(function(require) {
var Backbone = require('backbone');
var testTemplate = require('hbs!templates/test');
var router = Backbone.View.extend({
el: $('body'),
template: testTemplate,
render: function() {
return $(this.el).html(this.template());
}
});
return router;
});
在第 25 行Handlebars
调用hbs.js
文件时找不到compile
函数
define(["handlebars"], function(Handlebars) {
var buildMap = {},
templateExtension = ".hbs";
return {
// http://requirejs.org/docs/plugins.html#apiload
load: function (name, parentRequire, onload, config) {
// Get the template extension.
var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension);
if (config.isBuild) {
// Use node.js file system module to load the template.
// Sorry, no Rhino support.
var fs = nodeRequire("fs");
var fsPath = config.dirBaseUrl + "/" + name + ext;
buildMap[name] = fs.readFileSync(fsPath).toString();
onload();
} else {
// In browsers use the text-plugin to the load template. This way we
// don't have to deal with ajax stuff
parentRequire(["text!" + name + ext], function(raw) {
// Just return the compiled template
****HERE onload(Handlebars.compile(raw));
});
}
},
// http://requirejs.org/docs/plugins.html#apiwrite
write: function (pluginName, name, write) {
var compiled = Handlebars.precompile(buildMap[name]);
// Write out precompiled version of the template function as AMD
// definition.
write(
"define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" +
"return Handlebars.template(" + compiled.toString() + ");\n" +
"});\n"
);
}
};
});
该Handlebars
变量为我提供了 Handlebars 环境,但其中有一个额外的层,所以我必须将该行更改为Handlebars.default.compile(raw)
. 那个物体来自哪里,default
我该如何摆脱它?我不会担心,但如果我将这个项目拉到其他地方,我总是必须记住这样做。