Skip to content
This repository

RemoteActions

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.

Example:

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])
  @product.destroy

  # 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 => @product.name }
  end
end

In the Javascript:

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

    // 'this' (the context) is set to the element that triggered this RemoteAction
    this.up("div.product_entry").remove();

    $("flashArea").update("Product " + data.productName + " was removed.");
  }
});
Something went wrong with that request. Please try again.