Sometimes there are times when you want to use Rails' built-in RJS features, but without hitting the server. For simplicity sake, let's imagine that you want to visually highlight an area of the page when a user clicks on a link, but you don't want to make a call to the server for something as simple as this. Well you can do just that using the link_to_function helper in the view.
link_to_function
link_to_function is normally used to provide a clickable link on your HTML that will call a specified JavaScript function. However it can also take a page block in exactly the same way that you use RJS templates. When the link is clicked, it will execute the JavaScript generated by the RJS block. Take this example...
‹div id="menu">Make me flash!‹/div›
‹div id="highlight_link"›
<%= link_to_function "Click me!" do |page|
page['menu'].visual_effect :highlight
page['highlight_link'].remove
end %>
‹/div›
This little snippet of code will create a link that when clicked, will highlight the menu div and then remove the actual link from the page itself. Remember: you'll need to include the Prototype library for this to work, by adding ‹%=javascript_include_tag :defaults %› in the ‹head› of your HTML page.
Obtrusive?
Some people don't like this approach, as it creates "obtrusive" JavaScript. "Obtrusive" means that the JavaScript code is mixed in with the HTML rather than being abstracted out. It, also isn't very "Railsy" using it in the view. But most of Rails' JavaScript helpers create obtrusive JavaScript, so it depends upon how puritanical you want to be. For a quick way of manipulating the DOM, this is a simple and easy time-saving method to use.
1 comment:
wow!!!
I am looking for this for 5 days!!
Post a Comment