![]() |
# Module: BivouacHelpers::JavaScriptView [ "README", "AUTHORS", "COPYING", "lib/bivouac/helpers/view/goh/base.rb", "lib/bivouac/helpers/view/goh/form.rb", "lib/bivouac/helpers/view/goh/html.rb", "lib/bivouac/helpers/view/goh/tooltip.rb", "lib/bivouac/helpers/view/goh/scriptaculous.rb", "lib/bivouac/helpers/view/goh/javascript.rb", nil].each do JavaScriptGenerator.view_html BivouacHelpers.view_html BivouacHelpers::TooltipView.view_html BivouacHelpers::ScriptAculoUsView.view_html BivouacHelpers::BaseView.view_html BivouacHelpers::JavaScriptView.view_html BivouacHelpers::HtmlView.view_html BivouacHelpers::FormView.view_html end |
bivouac/helpers/view/html
Escape carrier returns and single and double quotes for JavaScript segments.
[ show source ]
# File lib/bivouac/helpers/view/goh/javascript.rb, line 202 202: def escape_javascript(javascript) 203: (javascript || '').gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" } 204: end
Returns a JavaScript tag with the block inside. Example:
javascript_tag( "alert('Hello World!')", :defer => 'true' )
Returns:
<script defer="true" type="text/javascript"> //<![CDATA[ alert('Hello World!') //]]> </script>
[ show source ]
# File lib/bivouac/helpers/view/goh/javascript.rb, line 218 218: def javascript_tag( content, options = {} ) 219: options[:type] = "text/javascript" 220: script( options ) do 221: "//<![CDATA[\n" + content + "\n//]]>" 222: end 223: end
Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact.
The function argument can be omitted in favor of an update_page block, which evaluates to a string when the template is rendered (instead of making an Ajax request first).
Examples:
link_to_function "Greeting", "alert('Hello world!')"
Produces:
<a onclick="alert('Hello world!'); return false;" href="#">Greeting</a> link_to_function(image_tag("delete"), "if (confirm('Really?')) do_delete()")
Produces:
<a onclick="if (confirm('Really?')) do_delete(); return false;" href="#"> <img src="/images/delete.png?" alt="Delete"/> </a> link_to_function("Show me more", nil, :id => "more_link") do |page| page[:details].visual_effect :toggle_blind page[:more_link].replace_html "Show me less" end
Produces:
<a href="#" id="more_link" onclick="try { $("details").visualEffect("toggle_blind"); $("more_link").update("Show me less"); } catch (e) { alert('RJS error:\n\n' + e.toString()); alert('$(\"details\").visualEffect(\"toggle_blind\"); \n$(\"more_link\").update(\"Show me less\");'); throw e }; return false;">Show me more</a>
[ show source ]
# File lib/bivouac/helpers/view/goh/javascript.rb, line 273 273: def link_to_function( name, *args, &block ) 274: html_options = args.last.is_a?(Hash) ? args.pop : {} 275: function = args[0] || '' 276: 277: function = update_page( &block ) if block_given? 278: 279: a( html_options.merge({ 280: :href => html_options[:href] || "#", 281: :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function}; return false;" 282: }) ) do 283: name 284: end 285: end
Returns a link to a remote action defined by options[:url] 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.
Examples:
link_to_remote "Delete this post", :update => "posts", :url => R(Destroy, 1) link_to_remote(image_tag("refresh"), :update => "emails", :url => R(ListEmails)
You can also specify a hash for options[:update] to allow for easy redirection of output to an other DOM element if a server-side error occurs:
Example:
link_to_remote "Delete this post", :url => R(Destroy, 1) :update => { :success => "posts", :failure => "error" }
Optionally, you can use the options[:position] parameter to influence how the target DOM element is updated. It must be one of :before, :top, :bottom, or :after.
To access the server response, use request.responseText, to find out the HTTP status, use request.status.
Example:
link_to_remote word, :url => R(Undo, word_counter) :complete => "undoRequestCompleted(request)"
The callbacks that may be specified are (in order):
: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. |
:success: | Called when the XMLHttpRequest is completed, and the HTTP status code is in the 2XX range. |
:failure: | Called when the XMLHttpRequest is completed, and the HTTP status code is not in the 2XX range. |
:complete: | Called when the XMLHttpRequest is complete (fires after success/failure if they are present). |
You can further refine :success and :failure by adding additional callbacks for specific status codes.
Example:
link_to_remote word, :url => R(Action), 404 => "alert('Not found...? Wrong URL...?')", :failure => "alert('HTTP Error ' + request.status + '!')"
A status code callback overrides the success/failure handlers if present.
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.
You can customize further browser side call logic by passing in JavaScript code snippets via some optional parameters. In their order of use these are:
:confirm: | Adds confirmation dialog. |
:condition: | Perform remote request conditionally by this expression. Use this to describe browser-side conditions when request should not be initiated. |
:before: | Called before request is initiated. |
:after: | Called immediately after request was initiated and before :loading. |
:submit: | Specifies the DOM element ID that‘s used as the parent of the form elements. By default this is the current form, but it could just as well be the ID of a table row or any other DOM element. |
[ show source ]
# File lib/bivouac/helpers/view/goh/javascript.rb, line 371 371: def link_to_remote(name, options = {}, html_options = {}) 372: link_to_function(name, remote_function(options), html_options) 373: end
Observes the field with the DOM ID specified by field_id and makes an Ajax call when its contents have changed.
Required options are either of:
:url: | url_for-style options for the action to call when the field has changed. |
:function: | Instead of making a remote call to a URL, you can specify a function to be called instead. |
Additional options are:
:frequency: | The frequency (in seconds) at which changes to this field will be detected. Not setting this option at all or to a value equal to or less than zero will use event based observation instead of time based observation. |
: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. If you specify a string without a "=", it‘ll be extended to mean the form key that the value should be assigned to. So :with => "term" gives "’term’=value". If a "=" is present, no extension will happen. |
:on: | Specifies which event handler to observe. By default, it‘s set to "changed" for text fields and areas and "click" for radio buttons and checkboxes. With this, you can specify it instead to be "blur" or "focus" or any other event. |
Additionally, you may specify any of the options documented in link_to_remote.
[ show source ]
# File lib/bivouac/helpers/view/goh/javascript.rb, line 420 420: def observe_field(field_id, options = {}) 421: if options[:frequency] && options[:frequency] > 0 422: build_observer('Form.Element.Observer', field_id, options) 423: else 424: build_observer('Form.Element.EventObserver', field_id, options) 425: end 426: end
Periodically calls the specified url (options[:url]) every options[:frequency] seconds (default is 10). Usually used to update a specified div (options[:update]) with the results of the remote call. The options for specifying the target with :url and defining callbacks is the same as link_to_remote.
[ show source ]
# File lib/bivouac/helpers/view/goh/javascript.rb, line 380 380: def periodically_call_remote(options = {}) 381: frequency = options[:frequency] || 10 # every ten seconds by default 382: code = "new PeriodicalExecuter(function() {#{remote_function(options)}}, #{frequency})" 383: javascript_tag(code) 384: end
Returns the JavaScript needed for a remote function. Takes the same arguments as link_to_remote.
Example:
select( :id => "options", :onChange => remote_function( :update => "options", :url => R(Update), :onSuccess => visual_effect( :highlight, 'my_element' ) ) ) do option( "Hello", :value => 0 ) option( "World", :value => 1 ) end
[ show source ]
# File lib/bivouac/helpers/view/goh/javascript.rb, line 442 442: def remote_function(options) 443: javascript_options = options_for_ajax(options) 444: 445: update = '' 446: if options[:update] && options[:update].is_a?(Hash) 447: update = [] 448: update << "success:'#{options[:update][:success]}'" if options[:update][:success] 449: update << "failure:'#{options[:update][:failure]}'" if options[:update][:failure] 450: update = '{' + update.join(',') + '}' 451: elsif options[:update] 452: update << "'#{options[:update]}'" 453: end 454: 455: function = update.empty? ? 456: "new Ajax.Request(" : 457: "new Ajax.Updater(#{update}, " 458: 459: function << "'#{options[:url]}'" 460: function << ", #{javascript_options})" 461: 462: function = "#{options[:before]}; #{function}" if options[:before] 463: function = "#{function}; #{options[:after]}" if options[:after] 464: function = "if (#{options[:condition]}) { #{function}; }" if options[:condition] 465: function = "if (confirm('#{escape_javascript(options[:confirm])}')) { #{function}; }" if options[:confirm] 466: 467: return function 468: end
Yields a JavaScriptGenerator and returns the generated JavaScript code. Use this to update multiple elements on a page in an Ajax response. See JavaScriptGenerator for more information.
[ show source ]
# File lib/bivouac/helpers/view/goh/javascript.rb, line 228 228: def update_page( &block ) 229: JavaScriptGenerator.new( self, &block ).to_s 230: end
Works like update_page but wraps the generated JavaScript in a <script> tag. See JavaScriptGenerator for more information.
[ show source ]
# File lib/bivouac/helpers/view/goh/javascript.rb, line 234 234: def update_page_tag( options = {}, &block ) 235: javascript_tag update_page( &block ), options 236: end