Skip to content

Instantly share code, notes, and snippets.

@timoxley
Created August 1, 2012 17:02
Show Gist options
  • Save timoxley/3228783 to your computer and use it in GitHub Desktop.
Save timoxley/3228783 to your computer and use it in GitHub Desktop.
backbone handlebars helper, allows child views to be initialised from templates ala Ember
Handlebars.registerHelper 'view', (viewPath, options) ->
# use Backbone.View if not supplied a backbone view subclass
unless viewPath
viewPath = 'Backbone.View'
return 'No View'
View = viewPath.split('.').reduce (previous, current) ->
return previous[current]
, window
view = new View(options.hash)
el = view.el
id = el.id
# collect references to views so we can manage lifecycle
View._instances = View._instances || []
View._instances.push(view)
unless id
# get id from view path
id = 'view-' + viewPath.split('.').map (e) ->
e.toLowerCase()
.join('-')
id += '-' + View._instances.length
#TODO: implement a rendering queue rather than relying on setTimeout render order
setTimeout(((id, view) ->
# swap out handlebars rendered placeholder with actual view element
$("##{id}").replaceWith(view.el)
view.render()
).bind(this, id, view), 0)
tagName = options.hash.tagName || 'div'
className = options.hash.tagName || ''
return new Handlebars.SafeString("<#{tagName} class='placeholder #{className}' id='#{id}'></#{tagName}>")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment