public
Description: JavaScript Application Framework - JS library only
Home | Edit | New

Custom View Helpers

Custom view helpers are a way to use the ERB view helper syntax with your own custom or composite views. This allows for cleaner RHTML code by segregating the view code into its own helper. In addition, you can use view helpers to create view templates for assigning outlets in your custom views. Without view helpers, you need to programmatically create view markup inside your custom view, either during initialization or any time there-after.

Creating Custom View Helpers

To create a custom view helper, you need to create a ruby file in your client/lib directory. The name of the file is not important, but for this example we’ll be using helpers.rb.

In helpers.rb add the following code:

view_helper :demo_view do
  view 'MyApp.CustomView'
  property :content

  css_class_names << 'my-app-custom-view'
  @inner_html = 'This text is inside my view div.'
end

Now, in english.lproj/body.rhtml (or any other RHTML file), you can use this view as so:

<%= demo_view :bind => { :content => 'MyApp.mainController.customViewContent' } %>

Gotchas

If you’re going to use declared outlets (function declared .outletFor() during object definition), you must define the @inner_html instance variable in your view helper code with the HTML needed by your outlet declarations. If you fail to do this, the outlet will not be able to find its DOM node at run-time (i.e., this.outlet('name') will return null)

See Also

SproutCore contain many examples of view helpers. You can find them in sproutcore/lib/*_view*.rb

Last edited by bjc, Sun Oct 12 08:36:17 -0700 2008
Home | Edit | New
Versions: