Skip to content

Instantly share code, notes, and snippets.

@plukevdh
Last active December 16, 2015 15:59
Show Gist options
  • Save plukevdh/5459841 to your computer and use it in GitHub Desktop.
Save plukevdh/5459841 to your computer and use it in GitHub Desktop.
add handlebars rendering/pre-caching to backbone
class Mustachio extends Backbone.View
templates: {}
render: ->
@templates[@templateName].call @, @renderContext()
lazyCompileFactory: (template_id, raw_template) ->
@templates[template_id] = (context) =>
compiled_template = Handlebars.compile(raw_template)
@templates[this.id] = compiled_template
compiled_template(context)
renderContext: ->
if @model then @model.toJSON() else {}
@prepare = ->
$('script[type="text/x-handlebars-template"]').each (i, item) =>
raw_template = item.textContent
raw_template = item.innerHTML unless raw_template # IE 8
@::lazyCompileFactory(item.id, raw_template)
window.Mustachio = Mustachio
$ ->
Mustachio.prepare()
class Mustachio extends Backbone.View
render: (template_id, context) ->
@templates[template_id].call @, context
@prepare = ->
templates = {}
$('script[type="text/x-handlebars-template"]').each ->
raw_template = this.textContent
raw_template = this.innerHTML unless raw_template # IE 8
templates[this.id] = Handlebars.compile(raw_template)
@::templates = templates
window.Mustachio = Mustachio
$ ->
Mustachio.prepare()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment