Created
February 1, 2011 19:46
-
-
Save donabrams/806506 to your computer and use it in GitHub Desktop.
Wrapper around jquery template that allows
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
// | |
// This is a wrapper around the jquery template library. | |
// | |
// The function to notice is: | |
// applyTemplate(data/{}, target/DOMNode, | |
// callback/function, keepPreviousTemplate/boolean) | |
// Once a template is instanced, calling this function will apply | |
// the template with the given data, then call the callback with | |
// no arguments. | |
// | |
// args should include any (1) of the following: url, templateString, template. | |
// If these aren't good enough for you, override _init (and remember to set ready). | |
// | |
// You can also override isCachingEnabled to avoid caching (jsps/dynamic happy). | |
// | |
// Requires a cache (see https://gist.github.com/806462) | |
// | |
$.templateWrapper = function(args) { | |
this.isCachingEnabled = true; | |
this.applyTemplate = function(data, target, callback, keepPreviousTemplate) { | |
this.getTemplate(function(template) { | |
this._applyTemplate(template, data, target, keepPreviousTemplate); | |
if (callback) { | |
callback(); | |
} | |
}); | |
}; | |
this._applyTemplate = function(template, data, target, keepPreviousTemplate) { | |
if (!keepPreviousTemplate) { | |
target.html(""); | |
} | |
$.tmpl(template, data).appendTo(target); | |
}; | |
this.getTemplate = function(callback) { | |
if (this.template) { | |
callback(this.template); | |
} else if (this.templateString) { | |
this.template = $.template(that.templateString)); | |
callback(this.template); | |
} else if (this.url) { | |
if (this.isCachingEnabled) { | |
var cache = $.templateWrapper.urlCache = | |
$.templateWrapper.urlCache || $.udel.cache(); | |
cache.getput(this.url, this.loadTemplate, callback); | |
} | |
else { | |
this.loadTemplate(callback); | |
} | |
} | |
}; | |
this.loadTemplate = function(callback) { | |
var that = this; | |
$.ajax({ | |
dataType: "text", | |
url: that.url, | |
type: "GET", | |
ifModified: that.isCachingEnabled, | |
success: function(tmplString) { | |
that.template = $.template(tmplString); | |
callback(that.template); | |
}, | |
error: function() { | |
that.template = "Error loading template from url."; | |
callback(that.template); | |
} | |
}); | |
}; | |
$.extend(true, this, args); | |
this._init(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment