Life on Rails » Technological travels in Flex, Air, RIA and life in general
Imagine a beautiful autumn park, and a bald ginger man reading books and playing guitar, and doing other stuff

Not writing the same js over and over again

I was doing a bunch of rjs stuff in rails, and lots of ajax goodness, and found myself constantly showing, and hiding the spinner and the update element (like a submit button, or other button)..

I’m a bit of a minimalist where possible and like to get rid of as much code as I can, and being as DRY as I can, and so I decided to make the following function:

  1. function updating_field(field_name, finished) {
  2. if (finished) {
  3. $(spinner).hide();
  4. $(update_ + field_name).show();
  5. } else {
  6. $(spinner).show();
  7. $(update_ + field_name).hide();
  8. }
  9. }

I simply call this method from the onclick method, or sumbit method of elements on the page and it tidies up my code considerably.

  1. <input type="submit" value="Save these changes" id="update_avatars2" onclick = "updating_avatars(false);" />

I can then call this code over and over again… In fact, I do, and I have many other helpers similar to this – which I’ll explore in other blog posts.

popups and link_to

Turns out that link_to handles popups,

You’d know this if you looked in the rdoc, but if you’re new to rails, you might not be down with that yet.

You can write code like:

  1. <%= link_to "pop me up", { :action => "show" }, :popup => [new_window,height=300,width=600] %>

I’m happier putting a javascript function in myself, and calling that, using onclick=>”popup(‘new_window’, 300, 600);” where function is something like:.

  1. function popup(window_name, url, p_width, p_height) {
  2. var new_window = window.open( url, window_name, "status = 1, height = " + p_height +", width = " + p_width );
  3. new_window.focus();
  4. }

I do this because then I can actually bring the window to the front (or specify more args, etc), I guess it could also be a matter of taste.

In fact, these days, I’m happier not using helpers like link_to for trivial stuff anyhow.