使用dojo AMD加载条件模板(html)

时间:2012-07-27 20:45:39

标签: javascript dojo 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 个答案:

答案 0 :(得分: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调用来获取资源,并在404错误时解析为undefined