Search code examples
javascriptruby-on-railsrjs

Is RJS evil and why?


I heard a bunch of rails developer saying that RJS is evil. I've never used it since I always managed to do what I wanted using classic javascript or jquery so I didn't pay attention. Now I'm getting into some legacy code and there's RJS all over the place.

So... is it true? What are the drawbacks/advantages of using RJS?


Solution

  • Let's talk about what RJS is before getting into whether or not it's evil.

    RJS applies the same level of abstraction to high functioning Javascript libraries that ActiveRecord supplies for SQL. However the RJS coverage for Javascript Libraries is nowhere near as complete as ActiveRecord's coverage of SQL adaptors.

    Rails ships with RJS support for Prototype/Script.aculo.us only. However, there are plugins either available or in development to support other Javascript libraries. For example JRails rewrites the Prototype based helpers to work with jQuery. Similar plugins exist for mootools and probably Dojo.

    The people who consider RJS to be evil, are generally the ones who aren't comfortable with it producing Prototype code, or those who feel they can accomplish things easier with raw Javascript.

    RJS isn't perfect, just as ActiveRecord isn't perfect, every so often you have to drop down to writing raw Javascript or SQL to get your job done. Again like ActiveRecord, the more comfortable you get with the advanced options the more you can accomplish without writing the raw code.

    One wonderful thing about RJS is that they are essentially views, that produce Javascript. It is very easy to extract out RJS into partials that can be included as necessary, either as responses to controllers or as a part of custom Javascript functions included in the page. This makes the code much more DRY allowing for simpler maintenance.

    Personally I use RJS frequently. I find it the perfect way to touch plenty of DOM elements at once. It comes with the double bonus of allowing me to create AJAX rich sites, without writing much Javascript. Then again I hate writing Javascript.