I've recently started learning Ruby on Rails, based on RoR3 beta/RC. I had earlier been developing applications using other frameworks (like Django), where the JavaScript had been written completely on my own.
When developing application using RoR, I get confused by the two possible ways of implementing JavaScript: the "pure" one (writing JavaScript and putting it in the <script>
tag) and writing RJS files.
Which of the approach should rather be used and when? If RJS, how do I implement particular actions like onChange
?
In rails you should use both approaches for different tasks. So do I. When I would like to execute ajax request, I use RJS because it simplifies the request and allows to write more powerful and flexible respond within .rjs file with a much less code. For example it is possible to use partials in it and to get access to ruby variables. When I would like to make a page more dynamic, I use plain javascript including it with javascript_include_tag
.
UPD.
This approach works in rails 3 the same way. It's possible to use it with JQuery and HAML. UJS in Rails 3 even simplifies it. The only thing you should do is to use jquery-ujs if you prefer Jquery over Prototype and proper file naming like create.js.haml
.
For example it possible to use server-side validation in AJAX requests with this approach.
In rails 3 the right way to do it is pure JS. RJS is too strict and you have to use Prototype or hack in some way to use it with jQuery. Rails 3 also promotes unobtrusive javascript. On AJAX requests you should return pure Javascript embed with ERB instead of using RJS.
Unfortunately since this change requires a lot of rework for older projects that used RJS some people will leave it be.
The RJS is actually depreciated in rails 3, you need a plugin to even work with it, so if you're starting now and you're lucky enough to start on rails 3 already, go the rails 3 way.
Here is a good example of the new UJS way: http://railscasts.com/episodes/205-unobtrusive-javascript
Good luck
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With