Monday, March 24, 2008

Creating element event handlers with RJS

If you're working with rails and ajax you probably familiar with the link_to_function helper. And especially with its ability to apply a block where you can put some RJS code. Sometimes it's pretty handy. Especially if you're not much javascript guru or just don't want to get dirty with it.

So, that's cool. But sometimes you might want to use RJS to write some events handling for say a form element. For example you've got a select box which switches different blocks on/off depends on what you choose and you need to wire the 'onchange' event with some logic. In a such case you can pass the :onchange value of the html_options argument in the 'select' helper method. The problem is that it applies a string, not a block where you can put in your RJS stuffs.

And the problem is solvable. There's another helper method which actually applies a block of rjs code and returns a string of compiled javascript code. It's name update_page. The link_to_function method calls it internally. For example you want to switch some blocks depend on a chosen language. This might look like that.

<%= select nil, nil, Language.to_options, {}, :onchange => update_page{ |page|
Language.all.each do |lang|
page << %{$("block-in-langage-#{lang.id}")[this.value == '#{lang.id}' ? 'show' : 'hide']();}
end
} %>

it's a little bit hacky, I've used this 'page << ' stuff and it's not probably a good rjs example. But I want to show the idea only. Whenever you need a javascript string and wish to write it in RJS, you can use the 'update_page' method and have it on.

No comments: