Module: ActionView::Helpers::JavascriptHelper

Defined in:
lib/action_view/helpers/javascript_helper.rb

Overview

Provides a set of helpers for calling Javascript functions and, most importantly, to call remote methods using what has been labelled Ajax. This means that you can call actions in your controllers without reloading the page, but still update certain parts of it using injections into the DOM. The common use case is having a form that adds a new element to a list without reloading the page.

To be able to use the Javascript helpers, you must either call <%= define_javascript_functions %> (which returns all the Javascript support functions in a <script> block) or reference the Javascript library using <%= javascript_include_tag "prototype" %> (which looks for the library in /javascripts/prototype.js). The latter is recommended as the browser can then cache the library instead of fetching all the functions anew on every request.

If you’re the visual type, there’s an Ajax movie demonstrating the use of form_remote_tag.

Constant Summary collapse

CALLBACKS =
[:uninitialized, :loading, :loaded, :interactive, :complete]
JAVASCRIPT_PATH =
File.join(File.dirname(__FILE__), 'javascripts')

Instance Method Summary collapse

Instance Method Details

#define_javascript_functionsObject

Includes the Action Pack Javascript library inside a single <script> tag.

Note: The recommended approach is to copy the contents of lib/action_view/helpers/javascripts/ into your application’s public/javascripts/ directory, and use javascript_include_tag to create remote <script> links.



111
112
113
114
115
116
117
# File 'lib/action_view/helpers/javascript_helper.rb', line 111

def define_javascript_functions
  javascript = '<script type="text/javascript">'
  Dir.glob(File.join(JAVASCRIPT_PATH, '*')).each do |filename|
    javascript << "\n" << IO.read(filename)
  end
  javascript << '</script>'
end

#escape_javascript(javascript) ⇒ Object

Escape carrier returns and single and double quotes for Javascript segments.



152
153
154
# File 'lib/action_view/helpers/javascript_helper.rb', line 152

def escape_javascript(javascript)
  (javascript || '').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }
end

#form_remote_tag(options = {}) ⇒ Object

Returns a form tag that will submit using XMLHttpRequest in the background instead of the regular reloading POST arrangement. Even though it’s using Javascript to serialize the form elements, the form submission will work just like a regular submission as viewed by the receiving side (all elements available in @params). The options for specifying the target with :url and defining callbacks is the same as link_to_remote.



78
79
80
81
82
83
84
85
# File 'lib/action_view/helpers/javascript_helper.rb', line 78

def form_remote_tag(options = {})
  options[:form] = true

  options[:html] ||= { }
  options[:html][:onsubmit] = "#{remote_function(options)}; return false;"

  tag("form", options[:html], true)
end

Returns a link that’ll trigger a javascript function using the onclick handler and return false after the fact.

Examples:

link_to_function "Greeting", "alert('Hello world!')"
link_to_function(image_tag("delete"), "if confirm('Really?'){ do_delete(); }")


29
30
31
32
33
34
# File 'lib/action_view/helpers/javascript_helper.rb', line 29

def link_to_function(name, function, html_options = {})
  (
    "a", name, 
    html_options.symbolize_keys.merge(:href => "#", :onclick => "#{function}; return false;")
  )
end

Returns a link to a remote action defined by options[:url] (using the url_for format) that’s called in the background using XMLHttpRequest. The result of that request can then be inserted into a DOM object whose id can be specified with options[:update]. Usually, the result would be a partial prepared by the controller with either render_partial or render_partial_collection.

Examples:

link_to_remote "Delete this post", :update => "posts", :url => { :action => "destroy", :id => post.id }
link_to_remote(image_tag("refresh"), :update => "emails", :url => { :action => "list_emails" })

By default, these remote requests are processed asynchronous during which various callbacks can be triggered (for progress indicators and the likes).

Example:

link_to_remote word,
    :url => { :action => "undo", :n => word_counter },
    :complete => "undoRequestCompleted(request)"

The callbacks that may be specified are:

:loading

Called when the remote document is being loaded with data by the browser.

:loaded

Called when the browser has finished loading the remote document.

:interactive

Called when the user can interact with the remote document, even though it has not finished loading.

:complete

Called when the XMLHttpRequest is complete.

If you for some reason or another need synchronous processing (that’ll block the browser while the request is happening), you can specify options[:type] = :synchronous.



70
71
72
# File 'lib/action_view/helpers/javascript_helper.rb', line 70

def link_to_remote(name, options = {}, html_options = {})  
  link_to_function(name, remote_function(options), html_options)
end

#observe_field(field_id, options = {}) ⇒ Object

Observes the field with the DOM ID specified by field_id and makes an Ajax when its contents have changed.

Required options are:

:frequency

The frequency (in seconds) at which changes to this field will be detected.

:url

url_for-style options for the action to call when the field has changed.

Additional options are:

:update

Specifies the DOM ID of the element whose innerHTML should be updated with the XMLHttpRequest response text.

:with

A Javascript expression specifying the parameters for the XMLHttpRequest. This defaults to ‘value’, which in the evaluated context refers to the new field value.

Additionally, you may specify any of the options documented in +link_to_remote.



139
140
141
# File 'lib/action_view/helpers/javascript_helper.rb', line 139

def observe_field(field_id, options = {})
  build_observer('Form.Element.Observer', field_id, options)
end

#observe_form(form_id, options = {}) ⇒ Object

Like observe_field, but operates on an entire form identified by the DOM ID form_id. options are the same as observe_field, except the default value of the :with option evaluates to the serialized (request string) value of the form.



147
148
149
# File 'lib/action_view/helpers/javascript_helper.rb', line 147

def observe_form(form_id, options = {})
  build_observer('Form.Observer', form_id, options)
end

#remote_function(options) ⇒ Object

:nodoc: for now



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/action_view/helpers/javascript_helper.rb', line 87

def remote_function(options) #:nodoc: for now
  javascript_options = options_for_ajax(options)

  function = options[:update] ? 
    "new Ajax.Updater('#{options[:update]}', " :
    "new Ajax.Request("

  function << "'#{url_for(options[:url])}'"
  function << ", #{javascript_options})"
  
  function = "#{options[:before]}; #{function}" if options[:before]
  function = "#{function}; #{options[:after]}"  if options[:after]
  function = "if (#{options[:condition]}) { #{function}; }" if options[:condition]

  return function
end