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

后端 未结 6 491
一整个雨季
一整个雨季 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:01

    You could use raw HTML-code or you might get HTML-code from DOM-element which should had rendered before this script

    1) raw HTML-code:

    var app = app || {};
    
    app.TreeView = Backbone.View.extend({
        tagName: 'ul',
        id: 'js-tree',
        template: _.template('
  • <%- Name %>
  • '), initialize: function() { this.render(); }, render: function () { this.model.each(this.renderRow, this); return this; }, renderRow: function(model) { var html = template(model); this.$el.append(html); return this; } });

    2) or HTML-code from rendered DOM-element:

    var app = app || {};
    
    app.TreeView = Backbone.View.extend({
        tagName: 'ul',
        id: 'js-tree',
        template: _.template($("#js-template-tree-item").html()),
        initialize: function() {
            this.render();
        },
        render: function () {
            this.model.each(this.renderRow, this);
            return this;
        },
        renderRow: function(model) {
            var html = template(model);
            this.$el.append(html);
            return this;
        }
    });
    

提交回复
热议问题