There are a few reasons I switched over to jQuery, and no I was not drinking the Kool-aid of joining the boat of the bigger players.
- The syntax made sense and was so much easier to write.
- It was faster at its traversing of the DOM compared to other libraries. I didn’t even try to use YUI, while it’s very hefty in what it does, it is extremely slow and seems to reek of code bloat.
- It’s continuously developed on as the community seems a lot stronger than that of Prototype’s.
For a while now, Rails has always been bundled with Prototype and Scriptaculous. Now, with the awesome rails generators, you can tell it to skip that:
rails new test-project -J # the -J skips Prototype builder
Now that Prototype isn’t in the project, you still need the jQuery drivers to interact with the UJS. To do so, it’s as easy as installing a gem from the jquery-ujs repo on github.
$ > gem 'jquery-rails', '>= 0.2.6'
The following are examples for creating objects in the database. Of course, these can be written to handle anything, but these are the bare examples that are typically used with UJS.
Gone are the old helpers:
And replaced by normal helpers with a few extra HTML5 type parameters:
form_for(@foo, :remote => true)
The “remote” paramter makes it a UJS form.
link_to(“My delete link”, “/delete/me“, data-method” => “delete”, “data-confirm” => “Are you sure?”)
The “data-“ params make it a UJS link.
So simple. These new parameters allow the rails.js file you included to recognize that there are remote forms or links on the page and handle accordingly.
No more RJS or old faux Prototype helpers. Now instead all you need to do in the controller is include the respond method to handle the xhr request.
The rails.js file only contains the ability to perform on what to do when you throw AJAX methods to it such as the standard beforeSend, success, complete, or error. This way you can write any custom functions to interact with these callbacks. Here is a base structure of how to handle just that:
The beforeSend action is great for letting the user know that something is happening. This can be done by changing the value of the submit button or adding a nice AJAX spinner graphic.
So the object was successfully saved to the database, now let’s take the data returned and append it to the DOM with an animation signifier.
I think the great thing about this new method is that there is no longer a reliance on knowing the RJS syntax. If you are already strong in writing jQuery syntax or just starting out, then this will become second nature. Removing the massive code from the DOM and extruding it into their own files makes debugging quicker and reduces complexity. This is just plain awesome, but that’s just my two cents.