euge edited this page Sep 13, 2010 · 2 revisions


While Rails provides a solution for updating the UI of a page, it is far from optimal. RJS encourages dynamically generating custom Javascript fragments on every request, adding unnecessary overhead to your server. It also complicates debugging code since it is passed into Javascript’s eval method as a string and executed.

Rather than relying on a tool like RJS to generate Javascript for updating the UI of your application, it is far more practical to write the Javascript once and place it into a file that can be efficiently cached by the browser.

behaveJS provides the ability to easily invoke methods defined in the Javascript from a Rails action utilizing the render_remote helper. This transparently integrates with AJAX requests performed using the behaveJS extensions to link_to and form_tag. There is also the added benefit that all RemoteActions invoked from the server have their contexts set to the element that triggered the AJAX request, allowing for easier DOM manipulation.


In a view:

<%= link_to("Destroy", product_path(@product), :method => :delete, :remote => true) %>

In a Rails controller:

def destroy
  @product = current_account.products.find(params[:id])

  # this simply renders a JSON response, that will be used to invoke 
  # the "productDeleted" method in the Javascript. When a block is provided,
  # the hash returned from it will be merged into the response, essentially allowing
  # for arguments to your RemoteAction.

  render_remote(:productDeleted) do
    { :productName => }

In the Javascript:

  productDeleted : function(response)
    var data = response.responseJSON;

    // 'this' (the context) is set to the element that triggered this RemoteAction

    $("flashArea").update("Product " + data.productName + " was removed.");