Sha256: dbb84f545b1a62e03e67a9acea87237b811ff343c1a77f7a28b35f0984fc8ff7

Contents?: true

Size: 1.64 KB

Versions: 1

Compression:

Stored size: 1.64 KB

Contents

module Merb
  module JavascriptMixin
  
    # escape text for javascript.
    def escape_js(javascript)
      (javascript || '').gsub('\\','\0\0').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }
    end
    
    def link_to_function(name, function)
      %{<a href="#" onclick="#{function}; return false;">#{name}</a>}
    end
    
    def js(data)
      if data.respond_to? :to_json
        data.to_json
      else
        data.inspect.to_json
      end
    end
    
    def require_js(*scripts)
      return nil if scripts.empty?
      scripts.inject('') do |memo,script|
        script = script.to_s
        memo << %Q|<script src="/javascripts/#{script=~/\.js$/ ? script : script+'.js' }" type="text/javascript">//</script>\n|
      end
    end
    
    def require_css(*scripts)
      return nil if scripts.empty?
      scripts.inject('') do |memo,script|
        script = script.to_s
        memo << %Q|<link href="/stylesheets/#{script=~/\.css$/ ? script : script+'.css' }" media="all" rel="Stylesheet" type="text/css"/>\n|
      end
    end
    
    def js_hash(options)
      '{' + options.map {|k, v| "#{k}:#{v}"}.join(', ') + '}'
    end
    
    def insert_html(id, html, options = {})
      position = options.fetch(:where, :before)
      "new Insertion.#{position.to_s.camel_case}('#{id}', '#{escape_js html}');"
    end
  
    def replace_html(id, html, options = {})
      "Element.update('#{id}', '#{escape_js html}');"
    end
    
    def hide(id)
      "$('#{id}').style.display = 'none';"
    end
    
    def show(id)
      "$('#{id}').style.display = 'block';"
    end
  
    def toggle(id)
      "Element.toggle('#{id}');"
    end
    
  end  
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
merb-0.0.7 lib/merb/mixins/javascript_mixin.rb