Reputation: 2717
How exactly does Rails render javascript code which is then executed by your browser? What is the data flow for this kind of thing.
Upvotes: 2
Views: 1141
Reputation: 1137
Rails renders Javascript Code as a callback to your browser when executing a Controller View. Using something called AJAX.
This happens when I click on an element or make a call through the browser using AJAX. AJAX allows you to make REMOTE browser calls without refreshing the page. Since you don't refresh the page, the only way to update the current page that you are looking at, is to have the controller render javascript back at the browser. The browser takes this javascript and executes it like code. The javascript can be used to do anything, from updating a number that is being displayed on the page, to removing something from the page, to adding in whole DIVs of information.
SO for instance, an example of this would be that you click on a delete button on a webpage to delete your post. The delete button sends a REMOTE message to the server, usually calling a METHOD in a VIEW CONTROLLER in your RAILS project. In our case, it just told the server to delete the post from the database. It does this and then the METHOD sees that since you asked for something in the remote manner, it chooses to render a JS response.
def destroy
@note = Note.find(params[:id])
@note_id = @note.id
@note.destroy
respond_to do |format|
format.html do // This is Rendered if the Message to Delete was NOT sent remotely
flash[:success] = "Note Deleted Successfully"
redirect_to root_path
end
format.js // Since we did send it Remotely, it then renders our Javascript Response
end
end
The javascript response would be, in our case of deleting something, a message that tells the browser to remove the DIV or page element that holds the thing you are telling it to delete.
$('#note-<%= @note_id %>').hide('slow', function(){ $('#note-<%= @note_id %>').remove(); }); // Hides the Post and then Removes it in a Smooth slow animation
$('.alert').slideUp('slow', function(){ $('.alert').remove(); }); // Shows the Alert with the alert
If we didn't render the call back to the browser, since the page didn't refresh, it would not show that the post was deleted until you manually refresh the page. This allows for pages to be more dynamic and save bandwidth, since you don't have to refresh the page, you then no longer have to pull down everything again from the server, allowing a more seamless user experience. And, since you use animations with JQuery, it can look impressive as well.
Here is a mini tutorial that I found that goes over using Rails 3 and JQuery in a very similar manner:
http://blog.bernatfarrero.com/jquery-and-rails-3-mini-tutorial/
Upvotes: 1