I’m using Backbone and therefore Underscore to render my templates. My templates get rendered in <script> tags and then I use jQuery to grab their html. My backbone view looks like this:
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!')
}
})
My Issue is I would like to only go and grab the html once and only once for this particular type of view so that if I have a lot of items it doesn’t go searching the html for this template each time.
Basically how do I properly store the template variable at the ItemView object level (not instance of the view) keeping in mind that the retrieval of the html has to wait until after page load (so that I can guarantee the template html is available).
You can build a very simple object that caches the templates for you:
Then in your view, you can call
TemplateCache.getand pass in your template selector.The first time you call
TemplateCache.getfor 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
TemplateCacheobject in my Backbone.Marionette framework: https://github.com/derickbailey/backbone.marionette