2014-01-09 44 views
0

我想在我的js項目中使用backbone,requirejs和handlebars創建一種模板加載器類。RequireJs導出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]確實NOT包含已編譯的模板...

你能幫助我嗎?

編輯

後得到一些建議。在聊天更新更多的細節問題:

我想要做到的,是編譯車把模板只有一次,第一次他們是調用。

我期望的是能夠在代碼的某處執行: templatemanager.addTemplate('path','name'); //用requirejs加載文件,用句柄編譯並將它存儲在模板管理器中,並將其存儲在模板管理器

以及其他地方,可能在許多地方,以便能夠執行類似於 templatemanager.getTemplate('name');

返回編譯的句柄模板。

我相信由於requirejs的異步性質,我必須在addtemplate和getTemplate上使用延遲對象和promise來「做某件事」。

那是什麼東西?

編輯2

我部分地解決重構的功能。我寫在這裏,如果別人有同樣的問題:

addTemplate : function (path,name) 
    {   
     var deferred = $.Deferred(); 

     require([path],function(tpl){ 
     _templates[name] = Handlebars.compile(tpl);           
     deferred.resolve(_templates[name]);      
     }); 

     return deferred.promise(); 
    } 

回答

3

問題是,那需要功能是異步的。它的回調是在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'); 
} 

載入多個模板

變種deferredArray = [];

for (...) { 
    deferredArray.push(addTemplate(path, name)); 
} 
$.when.apply($, deferredArray).then(function(result) { 
    console.log('template added'); 
}); 
+0

你能解釋一些嗎?我無法理解一種方法來「合併」jquery延遲/承諾(例如)與我的代碼。 此外,當requirejs完成加載時,作爲第二個參數傳遞的函數被觸發。 但我不能通過該功能_templates變量 – Stormsson

+0

@Stormsson更新答案與一個例子。 –

+0

@Stormsson你不能傳遞你自己的參數來要求回調函數,因爲你不是那個調用這個回調函數的人。 RqeuireJs會調用此回調並傳遞所有參數。 –