[LRUG] Best practices for javascript in Rails apps

Tejas Dinkar tejas at c42.in
Wed Jul 17 21:44:52 PDT 2013


On Jul-17-2013, at 5:43 PM, Tim Cowlishaw <tim at timcowlishaw.co.uk> wrote:
> 
> Therefore, has anyone got any tips or tricks for writing maintainable,
> testable, well-factored javascript as part of a rails application
> which has reasonably complex client-side behaviour, but isn't a
> one-page app?

I had written a blog post about this about a year ago [1], although a lot of my opinions have changed since then :-p

But I usually agree with the following patterns:

1) Use CoffeeScript :-). At the very least, use Javascript to model different 'widgets' on your page, and keep a consistent syntax for binding this: new MyAppNamespace.Widget($(".my-container"))

2) Don't let the JS be the entry point to binding. After your HTML that creates the container, immediately add the javascript tag. We are using content_for to ensure the javascript is placed at the end of the document.

3) As much as possible, pass in data to the javascript class being created, do not leave data lying around in the view. So avoid data- as much as possible. <button data-product-id=53>Order</button> new MyApp.OrderButton($("button")) should become <button>Order</button>, new MyApp.OrderButton($("button"), 53).
Exception to this is multiple entities. Ex: <button data-product-id=53>Order</button><button data-product-id=54>Order</button>. Though the purist could argue that one could iterate through the buttons and bind individually.

4) As much as possible, do not do any searches in global DOM, except in the constructor (so $ should never show up in methods)

5) Avoid live bindings as much as possible. I've gotten into more live binding bugs, where (say) pjax refreshing the page caused double binding to happen, than I could care about.

6) For testing i've used jasmine-rails, but I'm not too happy with it. Any reasonably complex javascript will probably manipulate the DOM. And make AJAX queries, pass it through some sort of templating engine, etc… Jasmine rails relies on DOM fixtures, which I always felt quickly goes out of sync with the real DOM of your app. I've found it easier to just spin up a browser and write an integration/functional test than to maintain the javascript tests. YMMV of course.

[1] http://blog.gja.in/2012/06/eight-simple-rules-for-maintainable.html
--
Tejas Dinkar
http://www.nilenso.com
Nilenso Software (formerly the consulting arm of C42 Engineering)




More information about the Chat mailing list