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

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

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

6条回答
  •  闹比i
    闹比i (楼主)
    2021-02-03 12:59

    You could store the compiled template in a closure so that only the instances of ItemView can access it:

    (function() {
    
        var template;
    
        App.ItemView = Backbone.View.extend({
    
            className:'well',
    
            events: {
                'click .continue': 'handleContinueClick'
            },
    
            initialize: function() {
                this.render();
            },
    
            render: function() {
                template = template || _.template($("#ItemTemplate").html());
                $(this.el).html(template({model:this.model}));
            },
    
            handleContinueClick: function(e) {
                alert('Clicked!');
            }
    
        });
    
    })();
    

提交回复
热议问题