public
Last active

async template loading

  • Download Gist
1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13
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;
}
 
});
2.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
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);
}
 
}
 
}
 
}
3.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13
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;
}
 
});
5.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
(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));
});
}
})();

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

Please

(Sorry about my english I'm spanish)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.