module Nitro # A collection of useful Javascript helpers. This modules # integrates helpers for the following javascript libraries: # # * behaviour.js # * prototype.js # * effects.js # * dragdrop.js # * controls.js module JavascriptMixin private unless const_defined? :DEFAULT_JAVASCRIPT_FILES DEFAULT_JAVASCRIPT_FILES = [ 'js/behaviour.js', 'js/prototype.js', 'js/effects.js', 'js/dragdrop.js', 'js/controls.js' ] end # :section: behaviour.js def behaviour(id, js) @_behaviours ||= [] @_behaviours << [id, js] end # :section: prototype.js def live_request(id, options = {}) if href = options.delete(:href) behaviour "##{id}", %{ el.onclick = function() { new Ajax.Request('#{href}', #{hash_to_js(options)}); return false; } } else behaviour "##{id}", %{ el.onclick = function() { new Ajax.Request(el.href, #{hash_to_js(options)}); return false; } } end end alias_method :live, :live_request alias_method :async, :live_request # :section: script.aculo.us dragdrop.js # Make the element dragable. def draggable(id, options = {}) @_javascript ||= '' @_javascript << "\nnew Draggable('#{id}', #{hash_to_js(options)});" end # :section: script.aculo.us controls.js # Add autocomplete functionality to a text field. def auto_complete(id, options = {}) update = options[:update] || "#{id}_auto_complete" url = options[:url] || "#{id}_auto_complete" @_javascript ||= '' @_javascript << "\nnew Ajax.Autocompleter('#{id}', '#{update}', '#{url}');" # Turn off the browser's autocomplete functionality to avoid # interference. behaviour "##{id}", %{ el.autocomplete = 'off'; } end # :section: general javascript helpers. # Include external javascript file. def include_script(files = DEFAULT_JAVASCRIPT_FILES) code = '' for file in [files].flatten code << %|| end return code end # Escape carrier returns and single and double quotes for JavaScript segments. def escape_javascript(js) (js || '').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" } end # Converts a Ruby hash to a Javascript hash. def hash_to_js(options) '{' + options.map {|k, v| "#{k}:#{v}"}.join(', ') + '}' end # Emits the aggregated helper javascript. #-- # FIXME: refactor this! #++ def helper_script code = %| | end end end # * George Moschovitis