微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何正确存储一个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

原文地址:https://www.jb51.cc/js/154292.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐