Conditional RJS · Tuesday May 27, 2008 by Gerhard Lazu
Conditional RJS is difficult to understand for a newbie, but it starts making sense when you start thinking abour it.
First of all RJS is not Javascript. RJS is Ruby code that gets translated into Javascript. Take for example the following code:
if @delivery_locations.blank?
page[:previous_delivery_locations].remove if page[:previous_deliver_locations]
else
if page[:previous_deliver_locations]
page[:previous_delivery_locations].replace_html @delivery_locations
else
page.insert_html :top, 'delivery_details', @delivery_locations
end
It all makes perfect sense. Hang on. How can Ruby check if an element is on a page if page[:previous_delivery_locations] if it's server-side, not client-side? Again, Ruby only generates Javascript which then gets executed client-side. What we want in this case is something along the lines:
if @company_delivery_locations.blank?
page << "if ( $('previous_delivery_locations') ) {"
page[:previous_delivery_locations].remove
page << "}"
else
page << "if ( $('previous_delivery_locations') ) {"
page[:previous_delivery_locations].replace_html @delivery_locations
page << "}else{"
page.insert_html :top, 'delivery_details', @delivery_locations
page << "}"
end
Notice the page <<. Everything that follows is raw Javascript and gets inserted exactly as we write it. That's more like it!
Remember, if you aren't sure about your RJS, always check the generated source through your best friend Firebug (or well, just View Source), and double check if it's what you hoped for.
If you want to read more on the subject, take a look here: Conditional RJS Explained.