Created
February 8, 2012 12:24
-
-
Save DimitarChristoff/1768949 to your computer and use it in GitHub Desktop.
Loading a bunch of external templates through mootools
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
/* | |
--- | |
name: Asset.templates | |
description: lazy-loading templates via Request.HTML and storing them for later under a key | |
authors: Dimitar Christoff | |
license: MIT-style license. | |
version: 1.1 | |
requires: | |
- Core/Request | |
- Core/Obect | |
- Core/Array | |
provides: | |
- Asset.templates | |
- Asset.templates.get | |
- Asset.templates.set | |
... | |
*/ | |
(function() { | |
var Templates = {}; | |
var Asset = this.Asset = this.Asset || {}; | |
Asset.templates = function(sources, options) { | |
if (!(this instanceof arguments.callee)) | |
return new Asset.templates(sources, options); | |
// load an array of templates as js script elements and fire an onComplete | |
this.options = Object.merge({ | |
path: "", | |
onComplete: Function.from, | |
onProgress: Function.from, | |
onFailure: Function.from | |
}, options); | |
this.counter = 0; | |
this.todo = sources.length; | |
var self = this; | |
var loadTemplate = function(source) { | |
var options = self.options; | |
new Request({ | |
url: [options.path, source.file].join(""), | |
onSuccess: function() { | |
Asset.templates.set(source.name, this.response.text); | |
self.counter++; | |
options.onProgress.call(self, source, self.counter); | |
if (self.counter == self.todo) | |
options.onComplete.call(self, self.counter); | |
}, | |
onFailure: function() { | |
options.onFailure.call(self, source, self.counter); | |
} | |
}).get(); | |
}; | |
Array.each(sources, loadTemplate); | |
}; | |
Asset.templates.get = function(name) { | |
return Templates[name] || ""; | |
}; | |
Asset.templates.set = function(name, body) { | |
return Templates[name] = body || ""; | |
}; | |
})(); | |
/* example use */ | |
new Asset.templates([{ | |
name: "user-edit", | |
file: "user-edit.html" | |
}, { | |
name: "user-create", | |
file: "user-create.html" | |
}], { | |
path: "static/templates/", | |
onProgress: function(template, count) { | |
console.log(template.file + " loaded..."); | |
}, | |
onComplete: function() { | |
window.fireEvent("templatesready"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
updated now, due to IE affecting HTML as it injects it into the DOM and reads it back, sometimes causing parser errors in _.js
_.template()
, I have moved the templates behind a private closure with a getter and a setter. Faster access this way anyway.