Created
November 22, 2011 18:43
-
-
Save davidguttman/1386494 to your computer and use it in GitHub Desktop.
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
# ViewLoader will load a list of partial views/templates from a json list (default is '/views/view_list.json'). Each view will be appended to the page in <script type="text/template"> tags with the id of the filename. One they have all been appended, the callback will be called. | |
class window.ViewLoader | |
constructor: (opts={}, @callback) -> | |
if (typeof opts) == "function" | |
@callback = opts | |
opts = {} | |
else | |
@callback = opts.success | |
@opts = opts | |
@opts.cachebuster = opts.cachebuster or false | |
@opts.viewBaseUrl = opts.viewBaseUrl or "/views" | |
@opts.viewListUrl = opts.viewListUrl or "#{opts.viewBaseUrl}/view_list.json" | |
@processViewList @opts.viewListUrl, @callback | |
idFromUrl: (url) -> | |
components = url.split('/') | |
filename = _.last components | |
id = filename.replace /\..+$/, '' | |
return "#{id}" | |
processViewList: (viewListUrl, callback) -> | |
$.getJSON viewListUrl, (urls) => | |
executeCallback = _.after urls.length, callback | |
for url in urls | |
@getView url, @opts.cachebuster, executeCallback | |
viewTemplate: _.template "<script type='text/template' id='<%= templateId %>' ><%= content %></script>" | |
getView: (viewUrl, cache, callback) -> | |
$.ajax | |
url: "#{@opts.viewBaseUrl}/#{viewUrl}" | |
cache: cache | |
success: (view) => | |
$('body').append @viewTemplate | |
templateId: @idFromUrl(viewUrl) | |
content: view | |
callback() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment