jQuery is an alternative to Prototype, which is the default javascript library inside Rails. Since RJS generates javascript based on prototype, you might think you can’t use jQuery in it. Although it’s technically true, you can still use jQuery by using the page.call feature of RJS. Here’s an example:
## test.js
$(function(){
...
};
function do_something_amazing {
... some slick jQuery code ...
};## something.rjs called using link_to_remote or form_for_remote:
page.call 'do_something_amazing'
Gotcha
A simple gotcha is if you include “function be_amazing {…};” inside the “$(function(){…};” you’ll get an undefined error.
Credits: I came across this approach while helping shipstar in the #rubyonrails IRC channel
UPDATE: Using RJS isn’t the best approach if you value unobtrusiveness. Here’s a copy/paste of some reasons why “RJS is evil”.
dfr|work: it’s directly coupled to your dom but isn’t in it.
dfr|work: i mean, what’s rjs? it’s just a callback thing. Just specify it when you’re making ajax request.
dfr|work: and if you need the data from server, specify it via json. It’s clean and simple.
Expect a follow-up to this explaining how to do this the right way.
