Last active
December 10, 2015 22:38
-
-
Save BenJam/4504134 to your computer and use it in GitHub Desktop.
A util function to load external templates into a backbone project.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
tpl = { | |
// Hash of preloaded templates for the app | |
templates:{}, | |
// Recursively pre-load all the templates for the app. | |
// This implementation should be changed in a production environment. All the template files should be | |
// concatenated in a single file. | |
loadTemplates:function (names, callback) { | |
var that = this; | |
var loadTemplate = function (index) { | |
var name = names[index]; | |
console.log('Loading template: ' + name); | |
$.get('tpl/' + name + '.html', function (data) { | |
that.templates[name] = data; | |
index++; | |
if (index < names.length) { | |
loadTemplate(index); | |
} else { | |
callback(); | |
} | |
}); | |
} | |
loadTemplate(0); | |
}, | |
// Get template by name from hash of preloaded templates | |
get:function (name) { | |
return this.templates[name]; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var templates = [ | |
'template1', | |
'template2', | |
'template3' | |
]; | |
tpl.loadTemplates(templates, function(){ | |
app = new AppRouter(); | |
Backbone.history.start(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This usage is for the document ready within the router but i imagine one could use
tpl.loadTemplate('template', function(){return});
in a Backbone.View's initialisation. Might be a slight performance hit on page change for larger template files though.