2012-07-27 44 views
2

所以我有這個簡單的要求:條件模板(HTML)裝載有道場AMD

require(['app/'+url,'dojo/text!content/'+url], function(module,template){ 
     if(module.init){ 
       module.init({ 
         container: panel, 
         containerId: 'contentTabs_' + idOp, 
         template: template 
       }); 
     } 
}); 

但模板可能不出現(有時它)。所以無論發生什麼,我都希望我的要求回調被執行。

什麼是AMD的方式來做到這一點?

謝謝你們。

回答

1

而不是使用dojo/text!的,寫自己的插件:

require(['foo/maybe!'+url], function(maybeTemplate) { 
    if (maybeTemplate === undefined) { 
    // it's there 
    } else { 
    // it's not there 
    } 
} 

foo/maybe必須解決與一個load : function (id, require, callback)成員的對象。

load(
    id,  // the string to the right of the ! 
    require, // AMD require; usually a context-sensitive require bound to the module making the plugin request 
    callback // the function the plugin should call with the return value once it is done 
) -> undefined 

您可以使用XHR調用來獲取資源和解決undefined上一個404錯誤。

+0

好答案,我來到了同樣的結論。順便說一下,是否需要返回一個Deferred? – 2012-08-06 19:25:31

+0

'require'返回'undefined' - 參見[here](http://livedocs.dojotoolkit.org/loader/amd#the-amd-api)。請記住,頂級API需要保持與其他每個實現AMD的JS API的兼容性。如果你需要在'require'中使用'Deferred',創建你自己的並在回調函數中解析它。 – McDowell 2012-08-06 19:48:04