Module: BivouacHelpers::JavaScriptView
- Defined in:
- lib/bivouac/helpers/view/goh/javascript.rb
Constant Summary collapse
- CALLBACKS =
[ :uninitialized, :loading, :loaded, :interactive, :complete, :failure, :success ] + ('100'..'599').to_a
Instance Method Summary collapse
-
#escape_javascript(javascript) ⇒ Object
Escape carrier returns and single and double quotes for JavaScript segments.
-
#javascript_tag(content, options = {}) ⇒ Object
Returns a JavaScript tag with the
block
inside. -
#link_to_function(name, *args, &block) ⇒ Object
Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact.
-
#link_to_remote(name, options = {}, html_options = {}) ⇒ Object
Returns a link to a remote action defined by
options[:url]
that’s called in the background using XMLHttpRequest. -
#observe_field(field_id, options = {}) ⇒ Object
Observes the field with the DOM ID specified by
field_id
and makes an Ajax call when its contents have changed. -
#periodically_call_remote(options = {}) ⇒ Object
Periodically calls the specified url (
options[:url]
) everyoptions[:frequency]
seconds (default is 10). -
#remote_function(options) ⇒ Object
Returns the JavaScript needed for a remote function.
-
#update_page(&block) ⇒ Object
Yields a JavaScriptGenerator and returns the generated JavaScript code.
-
#update_page_tag(options = {}, &block) ⇒ Object
Works like update_page but wraps the generated JavaScript in a <script> tag.
Instance Method Details
#escape_javascript(javascript) ⇒ Object
Escape carrier returns and single and double quotes for JavaScript segments.
202 203 204 |
# File 'lib/bivouac/helpers/view/goh/javascript.rb', line 202 def escape_javascript(javascript) (javascript || '').gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" } end |
#javascript_tag(content, options = {}) ⇒ Object
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>
218 219 220 221 222 223 |
# File 'lib/bivouac/helpers/view/goh/javascript.rb', line 218 def javascript_tag( content, = {} ) [:type] = "text/javascript" script( ) do "//<![CDATA[\n" + content + "\n//]]>\n" end end |
#link_to_function(name, *args, &block) ⇒ Object
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>
273 274 275 276 277 278 279 280 281 282 283 284 285 |
# File 'lib/bivouac/helpers/view/goh/javascript.rb', line 273 def link_to_function( name, *args, &block ) = args.last.is_a?(Hash) ? args.pop : {} function = args[0] || '' function = update_page( &block ) if block_given? a( .merge({ :href => [:href] || "#", :onclick => ([:onclick] ? "#{[:onclick]}; " : "") + "#{function}; return false;" }) ) do name end end |
#link_to_remote(name, options = {}, html_options = {}) ⇒ Object
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.
371 372 373 |
# File 'lib/bivouac/helpers/view/goh/javascript.rb', line 371 def link_to_remote(name, = {}, = {}) link_to_function(name, remote_function(), ) end |
#observe_field(field_id, options = {}) ⇒ Object
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.
420 421 422 423 424 425 426 |
# File 'lib/bivouac/helpers/view/goh/javascript.rb', line 420 def observe_field(field_id, = {}) if [:frequency] && [:frequency] > 0 build_observer('Form.Element.Observer', field_id, ) else build_observer('Form.Element.EventObserver', field_id, ) end end |
#periodically_call_remote(options = {}) ⇒ Object
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.
380 381 382 383 384 |
# File 'lib/bivouac/helpers/view/goh/javascript.rb', line 380 def periodically_call_remote( = {}) frequency = [:frequency] || 10 # every ten seconds by default code = "new PeriodicalExecuter(function() {#{remote_function()}}, #{frequency})" javascript_tag(code) end |
#remote_function(options) ⇒ Object
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
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 |
# File 'lib/bivouac/helpers/view/goh/javascript.rb', line 442 def remote_function() = () update = '' if [:update] && [:update].is_a?(Hash) update = [] update << "success:'#{[:update][:success]}'" if [:update][:success] update << "failure:'#{[:update][:failure]}'" if [:update][:failure] update = '{' + update.join(',') + '}' elsif [:update] update << "'#{[:update]}'" end function = update.empty? ? "new Ajax.Request(" : "new Ajax.Updater(#{update}, " function << "'#{[:url]}'" function << ", #{})" function = "#{[:before]}; #{function}" if [:before] function = "#{function}; #{[:after]}" if [:after] function = "if (#{[:condition]}) { #{function}; }" if [:condition] function = "if (confirm('#{escape_javascript([:confirm])}')) { #{function}; }" if [:confirm] return function end |
#update_page(&block) ⇒ Object
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.
228 229 230 |
# File 'lib/bivouac/helpers/view/goh/javascript.rb', line 228 def update_page( &block ) JavaScriptGenerator.new( self, &block ).to_s end |
#update_page_tag(options = {}, &block) ⇒ Object
Works like update_page but wraps the generated JavaScript in a <script> tag. See JavaScriptGenerator for more information.
234 235 236 |
# File 'lib/bivouac/helpers/view/goh/javascript.rb', line 234 def update_page_tag( = {}, &block ) javascript_tag update_page( &block ), end |