chaplinjs/chaplin — pull request #246 by tomcully (2012-10-30 05:40:40+00:00)
Title: Added the view as a data parameter to the template function call

I've modified the base render method to pass the current view into the options of the template when it is being rendered. This allows, for example, handlebars helpers like the following to be written:

Handlebars.registerHelper 'action', (context, options) ->
if not options.data.view?
console.error "Handlebars Helper 'action': No view is available in options.data.view - are you using the modified Chaplin?"

if typeof(options.data.view[context]) != 'function'
console.error "Handlebars Helper 'action': #{context} is not a method on view"

x = Math.round(Math.random()*99999999)

evt = options.hash.event
evt ?= 'click'

options.data.view.delegate evt, "#control-#{x}", options.data.view[context]
return new Handlebars.SafeString("id='control-#{x}'")

Allowing a handlebars template for a Chaplin view to do something like:

MouseOver

The code in a Chaplin view to handle that event:

module.exports = class WelcomeView extends PageView
template: WelcomeTemplate
className: 'home-page'

doms: (event) ->
console.log("Mouseover called: ",event)

Essentially, this helper allows us to bind an event on a DOM element in a view template directly to an instance method on its view, with a single line of code in the template. This is a lot simpler than creating an element and calling delegate in the view initializer, and the control auto-naming avoids problems with ID namespacing in large projects with many engineers.

This is a simple example but the benefits of having the current view instance available to helpers should be wide ranging.