How do I properly store a javascript template, so that it isn't instantiated multiple times

后端 未结 6 400
一整个雨季
一整个雨季 2021-02-03 12:44

I\'m using Backbone and therefore Underscore to render my templates. My templates get rendered in

6条回答
  •  春和景丽
    2021-02-03 13:15

    You can build a very simple object that caches the templates for you:

    
    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;
      }
    }
    

    Then in your view, you can call TemplateCache.get and pass in your template selector.

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

    The first time you call TemplateCache.get for a given selector, it will load it from the DOM. Any subsequent calls to get the template will load it from the cached version and prevent the extra DOM access call.

    FWIW: I have a much more robust version of the TemplateCache object in my Backbone.Marionette framework: https://github.com/derickbailey/backbone.marionette

提交回复
热议问题