Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created February 6, 2012 15:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mxriverlynn/1752642 to your computer and use it in GitHub Desktop.
Save mxriverlynn/1752642 to your computer and use it in GitHub Desktop.
async template loading
Backbone.View.extend({
template: 'my-view-template',
render: function(){
var that = this;
$.get("/templates/" + this.template + ".html", function(template){
var html = $(template).tmpl();
that.$el.html(html);
});
return this;
}
});
TemplateManager = {
templates: {},
get: function(id, callback){
var template = this.templates[id];
if (template) {
callback(template);
} else {
var that = this;
$.get("/templates/" + id + ".html", function(template)){
var $tmpl = $(template);
that.templates[id] = $tmpl;
callback($tmpl);
}
}
}
}
Backbone.View.extend({
template: 'my-view-template',
render: function(){
var that = this;
TemplateManager.get(this.template, function(template){
var html = $(template).tmpl();
that.$el.html(html);
});
return this;
}
});
(function(){
var promises = {};
// Cache the returned deferred/promise by the id of the template
// so that we can prevent multiple requests for the same template
// from making the ajax call.
//
// This code is only safe to run synchronously. There exists a
// race condition in this function, when run asynchronously,
// which would nullify the benefit under certain circumstances.
var loadTemplateAsync = function(tmpId){
var promise = promises[tmpId] || $.get("/templates/" + tmpId + ".html");
promises[tmpId] = promise;
return promise;
}
// Use jQuery to asynchronously load the template.
Backbone.Marionette.TemplateManager.loadTemplate = function(templateId, callback){
var tmpId = templateId.replace("#", "");
var promise = loadTemplateAsync(tmpId);
promise.done(function(template){
callback.call(this, $(template));
});
}
})();
@luismanolo
Copy link

Goood.
You should add it to the Backbone.Marionette proyect.

Please

(Sorry about my english I'm spanish)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment