我正在尝试使用backbone、requirejs 和handlebars 在我的js 项目中创建一种模板加载器类。
目标是从应用程序动态加载 Handlebars 模板,不从配置文件加载,例如
something.addTemplate('text!path/to/template','templateName');
在类里面我有这个:
[...]
addTemplate : function (path,name)
{
//_templates is an array defined outside
_templates[name] = require([path],function(tpl){
result = Handlebars.compile(tpl); //this is a Handlebar compiled template
return result;
});
console.log(_templates[name]); // returns the js code of the require function (i think)
},
[...other stuff...]
所以,在 addTemplate 函数 _templats[name] 的末尾,不包含已编译的模板...
你能帮我吗?
编辑
在聊天中得到一些建议后,我用更多详细信息更新了问题:
我想要实现的是仅在第一次调用它们时编译 Handlebars 模板一次。
我期望能够在代码中的某个地方执行以下操作: templatemanager.addTemplate('路径','名称');//使用requirejs加载文件,使用handlebars编译它并将其存储在模板管理器中
在其他地方,可能在很多地方,能够做类似的事情 templatemanager.getTemplate('name');
返回已编译的 Handlebars 模板。
我相信,由于 requirejs 的异步特性,我必须使用延迟对象和 promise 在 addtemplate 甚至 getTemplate 上“做一些事情”。
那是什么东西?
编辑2
我部分解决了重构函数的问题。如果其他人也有同样的问题,我写在这里:
addTemplate : function (path,name)
{
var deferred = $.Deferred();
require([path],function(tpl){
_templates[name] = Handlebars.compile(tpl);
deferred.resolve(_templates[name]);
});
return deferred.promise();
}
最佳答案
问题是,require 函数是异步的。它的回调在console.log之后执行。
您可能想使用promise .
addTemplate : function (path,name)
{
var deferred = $.Deferred();
//_templates is an array defined outside
_templates[name] = require([path],function(tpl){
result = Handlebars.compile(tpl); //this is a Handlebar compiled template
//return result;
deferred.resolve(result);
});
console.log(_templates[name]); // returns the js code of the require function (i think)
return deferred.promise();
},
加载单个模板
addTemplate(path, name).then(function() {
console.log('template added');
}
加载多个模板
var deferredArray = [];
for (...) {
deferredArray.push(addTemplate(path, name));
}
$.when.apply($, deferredArray).then(function(result) {
console.log('template added');
});
关于javascript - RequireJs 导出 Handlebars 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21021958/