[LRUG] Best practices for javascript in Rails apps

Tejas Dinkar tejas at c42.in
Thu Jul 18 04:55:42 PDT 2013


On Jul-18-2013, at 2:32 PM, Murray Steele <murray.steele at gmail.com> wrote:
> 
> On 18 July 2013 05:44, Tejas Dinkar <tejas at c42.in> wrote:
> 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?
> 
> 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.
>  
> I'm intrigued by this as it is the direct opposite of the approach and advice that seems to be favoured by most front-end type folk that I know.  e.g. HTML has loads of data attributes, JS is included / triggered in the head or very bottom of the page, the scripts themselves use (maybe live) css data attribute queries to find elements and enhance them.  
> 
> Can you elaborate on why you suggest your approach?  Is it performance related?  Or... ?


Not particularly. I've just found it easier to debug.

A more likely scenario would be something like this

<div class="product">
  <button>Order Now</button>
  <button>Add to Cart</button>
  <button>See Similar (in a popup)</button>
</div>

It's usually easier for me to have a single: new App.ProductWidget($(".product"), product_id);

And I use routes-js to generate routes from the CoffeeScript:
$.post(Routes.order_product_path(product_id, format: json))

Plus, when there is some extra data that comes to describe my product, say a color, I just need to change it in a single place: new App.ProductWidget($(".product"), product_id, color_id) or something.

Performance is a happy side effect, but it isn't a problem on my current project.
--
Tejas Dinkar
http://www.nilenso.com
Nilenso Software (formerly C42 Engineering)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20130718/c02227f7/attachment.html>


More information about the Chat mailing list