wycats / handlebars-site

56 stars 66 forks source link

Add a note to avoid compiling the same template multiple times #172

Open ChristopherDay opened 7 years ago

ChristopherDay commented 7 years ago

I've been using Handlebars in my app for a few years now, after adding a new feature that would update the UI every few seconds i noticed a small memory leak with this function:

    // OLD CODE
    parseTemplate: function (templateName, options) {
        var source   = $("#"+templateName).html();  
        var template = Handlebars.compile(source);
        var html    = template(options);
        return html;
    }

    // FIXED CODE
    compiledTemplates: {},
    parseTemplate: function (templateName, options) {
        if (!this.compiledTemplates[templateName]) {
            var source   = $("#"+templateName).html();
            var template = Handlebars.compile(source);
            this.compiledTemplates[templateName] = template;
        }
        var html    = this.compiledTemplates[templateName](options);
        return html;
    }

Now after a day or so i found https://github.com/wycats/handlebars.js/issues/271 and the correct way to do this, this is not explained anywhere (that i can see) in the documentation.