Last active
June 8, 2016 08:09
-
-
Save jonkemp/32657022c28da0b8f9b0 to your computer and use it in GitHub Desktop.
Load and cache external templates with jQuery and Underscore. Returns a promise. Useful for JavaScript MVC frameworks, such as Backbone.js.
This file contains hidden or 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
/* global $, _ */ | |
var TemplateManager = {}; | |
(function () { | |
'use strict'; | |
var cache = {}; | |
TemplateManager.template = function (path) { | |
var deferred = new $.Deferred(), | |
resolvePromise = function (template) { | |
deferred.resolveWith( null, [ _.template( template ) ] ); | |
}; | |
if (cache[path]) { | |
resolvePromise( cache[path] ); | |
} else { | |
$.get(path, function(data) { | |
cache[path] = data; | |
resolvePromise( data ); | |
}); | |
} | |
return deferred.promise(); | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment