2013-05-05 110 views
2

我已经看到了一些长篇大论的答案如何加载模板就该_underscore模板工具之类的渲染。我已经得到了以下工作:_underscore模板 - 从外部文件中加载模板

$.ajax({ 
    url: 'template.tmp', 
    type: 'get', 
    success: function(data) { 
     $('html').append(data); 
    } 
}); 

代码位于jQuery是加载之后,但使用的模板任何脚本之前。这会好吗,或者有没有理由加载这样的模板不是一个好主意? templates.tmp文件中有模板

<script type="text/template" id="tmpId"></script> 

标签。它们似乎很快被加载到DOM中。我准备批评这个实现,但我只想知道为什么。我能想到的唯一的事情可能是一些处理,如果“错误:”被调用而不是“成功:”。谢谢。

+1

由于'$。阿贾克斯()'是异步的,你可能会遇到其中一个使用这些模板的代码运行* *前的模板被加载到DOM的情况。此外,为什么不将模板包含在主HTML中以便开始? – robertklep 2013-05-05 15:45:15

+0

@robertklep我想我可以先用setInterval检查元素的模板相关函数,检查它们是否在DOM中,所以现在代码开始变长。这是一个非常有效的点,但应该检查。至于为什么。我到处都在阅读模块化方法是最佳实践。 – dewd 2013-05-05 15:58:17

+0

不错,模块化的方法是可取的,但一旦你有开始使用'setInterval'检查在DOM模板的可用性,你应该不知道是否是在这种使用情况下正确的做法:)或许呈现模板的代码可以要求 - 加载它们(并将它们存储在某个地方,如果它们需要重复渲染它们)? ([也许有用](http://stackoverflow.com/a/7542468/893780)) – robertklep 2013-05-05 16:03:29

回答

2

我决定制作我自己的OO基础的解决方案。这是构造函数:

var TemplateLoader = function(templatePath) { 
    this.template = templatePath; 
    this.loaded = false; 
    this.error = false; 
} 

而这些方法:

TemplateLoader.prototype.setReady = function (state) { 
    this.loaded = state; 
} 
TemplateLoader.prototype.setError = function (state) { 
    this.error = state; 
} 
TemplateLoader.prototype.isReady = function() { 
    return this.loaded; 
} 
TemplateLoader.prototype.isError = function() { 
    return this.error; 
} 
TemplateLoader.prototype.loadTemplate = function() { 
     templateLoader = this; 
     $.ajax({ 
      url: this.template, 
      type: 'get', 
      success: function(data) { 
       $('html').append(data); 
       templateLoader.setReady(true); 
      }, 
      error: function() { 
       templateLoader.setError(true); 
      } 
     }); 
} 

这是如何使用它:

templateLoader = new TemplateLoader('template.tmpl'); 
templateLoader.loadTemplate(); 

,并检查模板加载:

templateLoader.isReady() //true for loaded 
templateLoader.isError() //true for error loading template, eg. template doesn't exist 

同样,我会很感激的y对任何人可以通过此代码看到的问题提供反馈。如何检查附加到HTML的DOM对象。值得吗?