【问题标题】:Conditional template(html) loading with dojo AMD使用 dojo AMD 加载条件模板(html)
【发布时间】:2012-07-27 20:45:39
【问题描述】:

所以我有这个简单的要求:

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

但模板可能不存在(有时会存在)。所以无论发生什么,我都希望我的 require 回调被执行。

AMD 的方法是什么?

谢谢大家。

【问题讨论】:

    标签: javascript dojo 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 调用来获取资源并在出现 404 错误时解析为 undefined

    【讨论】:

    • 很好的答案 我得出了同样的结论。顺便问一下,是否需要返回一个 Defered?
    • require 返回undefined - 请参阅here。请记住,顶级 API 需要保持与所有其他实现 AMD 的 JS API 的兼容性。如果您需要将Deferredrequire 一起使用,请创建自己的并在回调函数中解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2011-09-21
    • 1970-01-01
    相关资源
    最近更新 更多