如何正确存储一个JavaScript模板,以便不被多次实例化

我使用 Backbone,因此 Underscore渲染我的模板.我的模板在< script>标签,然后我使用jQuery抓住他们的HTML.我的骨干视图看起来像这样:
App.ItemView = Backbone.View.extend({
    className:'well',events: {
        'click .continue': 'handleContinueClick',},initialize: function() {
        this.template = _.template($("#ItemTemplate").html())
        this.render()
    },render: function() {
        $(this.el).html(this.template({model:this.model}))
    },handleContinueClick: function(e) {
        alert('Clicked!')
    }
})

我的问题是,我想只为这个特定类型的视图一次只抓一次html,所以如果我有很多项目,它不会每次搜索这个模板的HTML.

基本上如何在ItemView对象级别(不是视图的实例)中正确存储模板变量,请牢记,html的检索必须等待页面加载(以便我可以保证模板html可用).

解决方法

您可以构建一个非常简单的对象来缓存您的模板:
TemplateCache = {
  get: function(selector){
    if (!this.templates){ this.templates = {}; }

    var template = this.templates[selector];
    if (!template){
      var tmpl = $(selector).html();
      template = _.template(tmpl);
      this.templates[selector] = template;
    }

    return template;
  }
}

然后在您的视图中,您可以调用TemplateCache.get并传入您的模板选择器.

Backbone.View.extend({
  template: "#ItemTemplate",render: function(){
    var template = TemplateCache.get(this.template);
    var html = template(this.model.toJSON());
    this.$el.html(html);
  }
});

第一次为给定的选择器调用TemplateCache.get时,它将从DOM加载它.任何随后的调用获取模板将从缓存版本加载它,并阻止额外的DOM访问调用.

FWIW:我的Backbone.Marionette框架中有一个更强大的TemplateCache对象版本:https://github.com/derickbailey/backbone.marionette

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...