| | 177 | |
|---|
| | 178 | # helper function to send a javascript command to the client. |
|---|
| | 179 | # options hash should have: |
|---|
| | 180 | # :action => (:insert, :replace, :delete, :empty, :formfill) |
|---|
| | 181 | # :target => DOM element. (string name) |
|---|
| | 182 | # :position => (:before, :top, :bottom, :after) |
|---|
| | 183 | # postion is only used in the insert routines |
|---|
| | 184 | # :formobject => ActiveRecord Object - values to fill into form |
|---|
| | 185 | # :formobject is used only by :formfill action |
|---|
| | 186 | # pass in a block of captured erb html for functions that make sense to do so. |
|---|
| | 187 | def send_ajax(options, &block) |
|---|
| | 188 | |
|---|
| | 189 | if block then |
|---|
| | 190 | # execute the block= |
|---|
| | 191 | # this code stolen from the capture helper |
|---|
| | 192 | buffer = eval("_erbout", block.binding) |
|---|
| | 193 | pos = buffer.length |
|---|
| | 194 | block.call |
|---|
| | 195 | |
|---|
| | 196 | # extract the block |
|---|
| | 197 | data = buffer[pos..-1] |
|---|
| | 198 | |
|---|
| | 199 | # replace it in the original with empty string |
|---|
| | 200 | buffer[pos..-1] = '' |
|---|
| | 201 | text = escape_javascript(data) |
|---|
| | 202 | end |
|---|
| | 203 | |
|---|
| | 204 | case options[:action] |
|---|
| | 205 | when :insert |
|---|
| | 206 | case options[:position] |
|---|
| | 207 | when :before |
|---|
| | 208 | "new Insertion.Before('#{options[:target]}', '#{text}')" |
|---|
| | 209 | when :top |
|---|
| | 210 | "new Insertion.Top('#{options[:target]}', '#{text}')" |
|---|
| | 211 | when :bottom |
|---|
| | 212 | "new Insertion.Bottom('#{options[:target]}', '#{text}')" |
|---|
| | 213 | when :after |
|---|
| | 214 | "new Insertion.After('#{options[:target]}', '#{text}')" |
|---|
| | 215 | else |
|---|
| | 216 | raise ArgumentError, "Invalid position, choose one of :before, :top, :bottom, :after" |
|---|
| | 217 | end |
|---|
| | 218 | when :replace |
|---|
| | 219 | "$('#{options[:target]}').innerHTML = '#{text}'" |
|---|
| | 220 | when :empty |
|---|
| | 221 | "$('#{options[:target]}').innerHTML = ''" |
|---|
| | 222 | when :delete |
|---|
| | 223 | "$('#{options[:target]}').parentNode.removeChild($('#{options[:target]}'))" |
|---|
| | 224 | when :formfill |
|---|
| | 225 | raise ArgumentError, ":formfill requires :formobject" unless options[:formobject] |
|---|
| | 226 | ret = '' |
|---|
| | 227 | objectname = options[:formobject].class.to_s.underscore |
|---|
| | 228 | for key,value in options[:formobject].attributes |
|---|
| | 229 | ret << "if ($('#{objectname}_#{key}')) { $('#{objectname}_#{key}').value = '#{escape_javascript(value.to_s)}'}\n" |
|---|
| | 230 | end |
|---|
| | 231 | return ret |
|---|
| | 232 | else |
|---|
| | 233 | raise ArgumentError, "Invalid action, choose one of :insert, :replace, :delete, :empty, :formfill" |
|---|
| | 234 | end |
|---|
| | 235 | |
|---|
| | 236 | end |
|---|