How to: use render :js

render :js is a fantastic way to further decrease the line of codes for rendering the response for XHR (XML HTTP Requests or simply Ajax/RJS calls).

The usual way to render the response for XHR requests is either using an rjs template or using the render :update block. I definitely prefer using the render :update option instead of creating an rjs view file because most of the times the response to an XHR request consists of just a few lines of code which easily goes in the controller’s action itself.

render :js goes one step further to use instead of render :update. In render :js, we just need to call this function and not to write a block thereby saving further couple of lines of code. However, I mainly see the great advantage of using render :js instead of render :update when you just have one or two lines of JS response to the XHR request. For greater lines of response I would still prefer to use render :update

For Example

using render :update

render :update do |page|
  page.call "alert('Hello World!')"
end

can simply be replaced using render :js

render :js => "alert('Hello World!')"


This entry was posted on Thursday, July 29th, 2010 at 4:49 am and is filed under ajax, rjs, rubyonrails. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

Your comment