Skip to content

Instantly share code, notes, and snippets.

@donabrams
Created October 21, 2011 14:04
Show Gist options
  • Select an option

  • Save donabrams/1303940 to your computer and use it in GitHub Desktop.

Select an option

Save donabrams/1303940 to your computer and use it in GitHub Desktop.
Deferred template class with optional caching and url fetching. Uses jqote2 (but easily changed).
define(["jquery", "jquery.jqote2", "jquery.deferredPipeline", "jquery.cache"],
function($, jqote2, deferredPipeline, cache) {
//
// This is a wrapper around the jqote2 template library.
//
// The function to notice is:
// applyTemplate(data/{}, target/DOMNode, keepPreviousTemplate/boolean)
//
var templateCache = null;
$.template = Class.extend({
isCachingEnabled: true,
init: function(args) {
if (args.template) {
this.template = args.template;
} else if (args.templateString) {
this.templateString = args.templateString;
} else if (args.url) {
this.url = args.url;
}
if (args.isCachineEnabled !== undefined) {
this.isCachineEnabled = args.isCachineEnabled;
}
this.templatePromise = this.getTemplate();
},
applyTemplate: function(data, target, keepPreviousTemplate) {
var that = this;
return deferredPipeline(
function() {
if (target.transitionOut && doTransitions) {
return target.hide(target.transitionOut, null, null);
}
},
function() {
return that.templatePromise;
},
function(template) {
if (!keepPreviousTemplate) {
target.html("");
target.transitionOut = that.transitionOut;
target.append(that.useTemplate(template, data));
if (that.transitionIn && doTransitions) {
target.show(that.transitionIn, null, null);
}
}
},
function() {
if (that.transitionOut) {
target.transitionOut = that.transitionOut;
}
}
);
},
getTemplate: function() {
if (this.template) {
return $.when(this.template);
}
if (this.templateString) {
this.template = this.compileTemplate(this.templateString);
return $.when(this.template);
}
if (this.url) {
if (this.isCachingEnabled) {
var cache = templateCache || new cache();
var that = this;
return deferredPipeline(
function() {
return cache.getput(this.url,
function() {
return that.loadTextFromUrl(that.url, that.isCachingEnabled);
});
},
function(templateString) {
that.template = that.compileTemplate(templateString);
}
);
}
else {
return deferredPipeline(
function() {
return that.loadTextFromUrl(that.url, that.isCachingEnabled);
},
function(templateString) {
that.template = that.compileTemplate(templateString);
}
);
}
}
var dfd = $.Deferred();
dfd.reject();
return dfd.promise();
},
loadTextFromUrl: function(url, isCachingEnabled) {
return $.ajax({
dataType: "text",
url: url,
type: "GET",
ifModified: isCachingEnabled
});
},
compileTemplate: function(templateString) {
return $.jqotec(templateString);
},
useTemplate: function(template, data) {
return $.jqote(template, data)
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment