RequireJs导出Handlebars模板

时间:2014-01-09 13:44:57

标签: javascript backbone.js requirejs handlebars.js

我正在尝试使用backbone,requirejs和handlebars在我的js项目中创建一种模板加载器类。

目标是从应用程序动态加载手柄模板,从配置文件中 NOT ,如

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] NOT 包含已编译的模板......

你可以帮帮我吗?

修改

在聊天中获得一些建议后,我会更新问题并提供更多详细信息:

我想要实现的是只在第一次调用它们时编译一次把手模板。

我期望能够在代码的某个地方做到:     templatemanager.addTemplate( '路径', '名称'); //使用requirejs加载文件,使用把手编译并将其存储在模板管理器中

和其他地方,可能在很多地方,能够做类似的事情     templatemanager.getTemplate( '姓名');

返回已编译的车把模板。

我相信由于requirejs的异步性质,我必须在addtemplate和甚至使用延迟对象和promise的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();
    }

1 个答案:

答案 0 :(得分:3)

问题是,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');
});