admin管理员组

文章数量:1291698

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 pletely 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?

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 pletely 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?

Share asked Jul 31, 2010 at 12:27 mhaligowskimhaligowski 2,22222 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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./episodes/205-unobtrusive-javascript

Good luck

本文标签: Rails 3 RJS vs JavaScriptStack Overflow