Topic: How to refactor this code into RJS helper?

Hi,

I've got the following code in my view, which toggles visiblity of an element and additionally toggles an image:

<%= link_to_function(image_tag("plus.gif", :title => "Add an assignment"), 
  "$('scenario_#{scenario.id}_form').toggle();" +
  "image = $$('#scenario_#{scenario.id} td.options img').first();" +
  "image.src = (image.src.match(/plus.gif/)) ?  '/images/minus.gif' : '/images/plus.gif';",
  :class => 'image') %>

I've tried to do this using RJS, but I kept getting various js errors.

I'd like to replace javascript with RJS and create a RJS helper for toggling images (last 2 lines of javascript), which would get an img element and image names as parameters.

How to do it? Thank you in advance

Re: How to refactor this code into RJS helper?

I don't think RJS will be much better here. It's not that good at "if" conditions or setting variables. Instead I recommend creating a javascript function in application.js and calling that. At least that will clean up the view.

Railscasts - Free Ruby on Rails Screencasts

Re: How to refactor this code into RJS helper?

Thanks!

I wasn't able to move much of the code to appplication.js - the first two lines use scenario object, and putting #{scenario.id} into appplication.js doesn't really work. I've created toggle_image(element) function out of the third line and now the whole code is a bit shorter.

Re: How to refactor this code into RJS helper?

You can pass the scenario id to the javascript function:

function do_something(scenario_id) {
  $('scenario_' + scenario_id + '_form').toggle();
  //...
}

<%= link_to_function(image_tag("plus.gif", :title => "Add an assignment"), "do_something('#{scenario.id}')" %>

Railscasts - Free Ruby on Rails Screencasts

Re: How to refactor this code into RJS helper?

Thank you! Now it's much cleaner and shorter.