Skip to content

Instantly share code, notes, and snippets.

@davidguttman
Created November 22, 2011 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidguttman/1386494 to your computer and use it in GitHub Desktop.
Save davidguttman/1386494 to your computer and use it in GitHub Desktop.
# 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