Skip to content

Instantly share code, notes, and snippets.

@jwietelmann
Created July 9, 2012 17:41
Show Gist options
  • Save jwietelmann/3077818 to your computer and use it in GitHub Desktop.
Save jwietelmann/3077818 to your computer and use it in GitHub Desktop.
Handlebars view helpers build out tree of View objects
# patched version of Handlebars with helper - passes current view to next context
Handlebars.registerHelper "with", (context, options) ->
context.view = this.view if this.view # the patch
options.fn context
# patched version of Handlebars each helper - passes current view to next context
Handlebars.registerHelper "each", (context, options) ->
fn = options.fn
inverse = options.inverse
ret = ""
if context and context.length > 0
for newContext in context
newContext.view = this.view if this.view # the patch
ret = ret + fn(newContext)
else
ret = inverse(this)
ret
Handlebars.registerHelper "bone", (stubId, options) ->
options = options.hash
klass = options.type || "Handlebone.View"
delete options.type
if variant = options.variant
stubId += variant
delete options.variant
options.model = this.model || this
options.parent = this.view
this.view.addChild stubId, klass, options
new Handlebars.SafeString '<div id="stub-' + stubId + '" class="viewStub"></div>'
class Handlebone.View extends Backbone.View
postInit: (options) -> # override
initialize: (options) ->
@template = options.template if options.template
@parent = options.parent if options.parent
@children = {}
if options.renderOn
_.bindAll this, "render"
for event in options.renderOn.split " "
@model.bind event, @render
@postInit options
_data: ->
data = @model.toJSON()
data.model = @model
data.view = this
if @model.collections
for name in @model.collections
data[name] = @model[name].models
data
addChild: (stubId, klass, options) ->
@children[stubId] ||= new window[klass](options)
_renderChildren: ->
for stubId, view of @children
@$el.find("#stub-#{stubId}").replaceWith(view.render())
render: ->
@$el.html(Handlebone.templates[@template] @_data())
@_renderChildren()
@delegateEvents()
@$el
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment