rails best practices where to place unobtrusive javascript

Posted by nathanvda on Stack Overflow See other posts from Stack Overflow or by nathanvda
Published on 2010-05-23T11:31:19Z Indexed on 2010/05/23 11:40 UTC
Read the original article Hit count: 435

Filed under:
|
|
|
|

Hi there,

my rails applications (all 2.3.5) use a total mix of inline javascript, rjs, prototype and jquery. Let's call it learning or growing pains. Lately i have been more and more infatuated with unobtrusive javascript. It makes your html clean, in the same way css cleaned it up.

But most examples i have seen are small examples, and they put all javascript(jquery) inside application.js

Now i have a pretty big application, and i am thinking up ways to structure my js. I like somehow that my script is still close to the view, so i am thinking something like

orders.html.erb
orders.js

where orders.js contains the unobtrusive javascript specific to that view. But maybe that's just me being too conservative :)

I have read some posts by Yehuda Katz about this very problem here and here, where he tackles this problem. It will go through your js-files and only load those relevant to your view. But alas i can't find a current implementation.

So my questions:

  • how do you best structure your unobtrusive javascript; manage your code, how do you make sure that it is obvious from the html what something is supposed to do. I guess good class names go a long way :)
  • how do you arrange your files, load them all in? just a few? do you use content_for :script or javascript_include_tag in your view to load the relevant scripts. Or ... ?
  • do you write very generic functions (like a delete), with parameters (add extra attributes?), or do you write very specific functions (DRY?). I know in Rails 3 there is a standard set, and everything is unobtrusive there. But how to start in Rails 2.3.5?

In short: what are the best practices for doing unobtrusive javascript in rails? :)

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about ruby