[LRUG] Best practices for javascript in Rails apps

Frederick Cheung frederick.cheung at gmail.com
Thu Jul 18 05:10:00 PDT 2013


On 17 Jul 2013, at 15:33, Alex Reis <alex at alexmreis.com> wrote:

> Hi Tim,
> 
> Personally, I've found that using CoffeeScript and Backbone's Views or Spine.js Controllers to wrap up the bits of javascript that go with a given Rails view/partial is a nice way to keep everything nice and tidy.
> 
> I construct the View/Controller in in-line JS (go ahead, say eeew, but it makes more sense to me than a separate JS file just to bootstrap a controller) normally passing in a DOM element that the rails view created.
> 
> I'll wire up my event handlers using the events array like you'd do in a normal view, which is way tidier than all the logic that ends up in your onload stuff in a .js file.
> 

I've also found backbone views/controllers to be rather useful. I've never used models in the full magic syncing way but I've found them useful as a way of separating crazy dom wrangling from the actual logic: controllers create views, views observe models/trigger events and models contain any required logic. I like the way that backbone seems to have achieved a balance between encouraging you to use a sensible structure, separation of concerns etc. without forcing too much of itself on you - it's very easy to only use the bits of it you want.

As far as how do views/controllers get created we've gone down the road of adding data attributes to body. There's a few lines of js that knows that if data-controller is admin/users and data-action is index then it should call Admin::Users.index. we have a couple of manifest files (admin.js, application.js for the regular consumer facing app, etc) so that we're not loading absolutely everything all the time.

There's still a slightly awkward feeling when I want to pass a larger chunk of data to the javascript. I normally end up with a inline javascript snippet setting window.foo but I've never felt very happy about that.

Fred


More information about the Chat mailing list