Skip to content
apotonick edited this page Sep 14, 2010 · 7 revisions

Unobstrusive JavaScript (UJS)

That’s separating markup and HTML, e.g. not putting JS into an onclick attribute but in a detached observer.

Apotomo widgets have built-in support for UJS by providing a capturing #collect_js in the view.

Example

A view item_list/display.html.haml might look like

= %ul#itemList
  = %li "Coffee"
  = %li "Peanut Butter"

- collect_js do
  "#itemList li".on('click', function() {...});

Page rendering

When the page containing that widget is rendered initially, all collect_js blocks are collected in a yield’able :apotomo_js variable.

Page update

Often widgets update themselves via AJAX. Apotomo takes care about copying the collect_js content to the existing block. So, widgets may invoke ujs over and over again, which should usually result in multiple observers for the same event.

You can

  • use your JavaScript framework to prevent double observers
  • instruct collect_js to render only once, like (REALLY?)
render :view => :display, :suppress_js => true

- collect_javascript do
  ...

Credits

Thanks to Nikolay V. Nemshilov [MadRabbit], the author of RightJS who spent hours explaining me all the bits and bytes of different JavaScript frameworks, UJS and inline JavaScript.