PageSourceSearch

https://www.retropacman.com/m/js/jquery_ujs.js

js retropacman.com collected 2026-10-03 02:38:30 UTC 12,712 bytes, 315 lines download raw bytes

1/**
2 * Unobtrusive scripting adapter for jQuery
3 *
4 * Requires jQuery 1.4.4 or later.
5 * https://github.com/rails/jquery-ujs
6
7 * Uploading file using rails.js
8 * =============================
9 *
10 * By default, browsers do not allow files to be uploaded via AJAX. As a result, if there are any non-blank file fields
11 * in the remote form, this adapter aborts the AJAX submission and allows the form to submit through standard means.
12 *
13 * The `ajax:aborted:file` event allows you to bind your own handler to process the form submission however you wish.
14 *
15 * Ex:
16 *     $('form').live('ajax:aborted:file', function(event, elements){
17 *       // Implement own remote file-transfer handler here for non-blank file inputs passed in `elements`.
18 *       // Returning false in this handler tells rails.js to disallow standard form submission
19 *       return false;
20 *     });
21 *
22 * The `ajax:aborted:file` event is fired when a file-type input is detected with a non-blank value.
23 *
24 * Third-party tools can use this hook to detect when an AJAX file upload is attempted, and then use
25 * techniques like the iframe method to upload the file instead.
26 *
27 * Required fields in rails.js
28 * ===========================
29 *
30 * If any blank required inputs (required="required") are detected in the remote form, the whole form submission
31 * is canceled. Note that this is unlike file inputs, which still allow standard (non-AJAX) form submission.
32 *
33 * The `ajax:aborted:required` event allows you to bind your own handler to inform the user of blank required inputs.
34 *
35 * !! Note that Opera does not fire the form's submit event if there are blank required inputs, so this event may never
36 *    get fired in Opera. This event is what causes other browsers to exhibit the same submit-aborting behavior.
37 *
38 * Ex:
39 *     $('form').live('ajax:aborted:required', function(event, elements){
40 *       // Returning false in this handler tells rails.js to submit the form anyway.
41 *       // The blank required inputs are passed to this function in `elements`.
42 *       return ! confirm("Would you like to submit the form with missing info?");
43 *     });
44 */
45
46(function($) {
47  // Shorthand to make it a little easier to call public rails functions from within rails.js
48  var rails;
49
50  $.rails = rails = {
51    // Link elements bound by jquery-ujs
52    linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]',
53
54    // Form elements bound by jquery-ujs
55    formSubmitSelector: 'form',
56
57    // Form input elements bound by jquery-ujs
58    formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])',
59
60    // Form input elements disabled during form submission
61    disableSelector: 'input[data-disable-with], button[data-disable-with], textarea[data-disable-with]',
62
63    // Form input elements re-enabled after form submission
64    enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled',
65
66    // Form required input elements
67    requiredInputSelector: 'input[name][required],textarea[name][required]',
68
69    // Form file input elements
70    fileInputSelector: 'input:file',
71
72    // Make sure that every Ajax request sends the CSRF token
73    CSRFProtection: function(xhr) {
74      var token = $('meta[name="csrf-token"]').attr('content');
75      if (token) xhr.setRequestHeader('X-CSRF-Token', token);
76    },
77
78    // Triggers an event on an element and returns false if the event result is false
79    fire: function(obj, name, data) {
80      var event = $.Event(name);
81      obj.trigger(event, data);
82      return event.result !== false;
83    },
84
85    // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm
86    confirm: function(message) {
87      return confirm(message);
88    },
89
90    // Default ajax function, may be overridden with custom function in $.rails.ajax
91    ajax: function(options) {
92      return $.ajax(options);
93    },
94
95    // Submits "remote" forms and links with ajax
96    handleRemote: function(element) {
97      var method, url, data,
98        dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType);
99
100      if (rails.fire(element, 'ajax:before')) {
101
102        if (element.is('form')) {
103          method = element.attr('method');
104          url = element.attr('action');
105          data = element.serializeArray();
106          // memoized value from clicked submit button
107          var button = element.data('ujs:submit-button');
108          if (button) {
109            data.push(button);
110            element.data('ujs:submit-button', null);
111          }
112        } else {
113          method = element.data('method');
114          url = element.attr('href');
115          data = element.data('params') || null; 
116       }
117
118        rails.ajax({
119          url: url, type: method || 'GET', data: data, dataType: dataType,
120          // stopping the "ajax:beforeSend" event will cancel the ajax request
121          beforeSend: function(xhr, settings) {
122            if (settings.dataType === undefined) {
123              xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
124            }
125            return rails.fire(element, 'ajax:beforeSend', [xhr, settings]);
126          },
127          success: function(data, status, xhr) {
128            element.trigger('ajax:success', [data, status, xhr]);
129          },
130          complete: function(xhr, status) {
131            element.trigger('ajax:complete', [xhr, status]);
132          },
133          error: function(xhr, status, error) {
134            element.trigger('ajax:error', [xhr, status, error]);
135          }
136        });
137      }
138    },
139
140    // Handles "data-method" on links such as:
141    // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
142    handleMethod: function(link) {
143      var href = link.attr('href'),
144        method = link.data('method'),
145        csrf_token = $('meta[name=csrf-token]').attr('content'),
146        csrf_param = $('meta[name=csrf-param]').attr('content'),
147        form = $('<form method="post" action="' + href + '"></form>'),
148        metadata_input = '<input name="_method" value="' + method + '" type="hidden" />';
149
150      if (csrf_param !== undefined && csrf_token !== undefined) {
151        metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />';
152      }
153
154      form.hide().append(metadata_input).appendTo('body');
155      form.submit();
156    },
157
158    /* Disables form elements:
159      - Caches element value in 'ujs:enable-with' data store
160      - Replaces element text with value of 'data-disable-with' attribute
161      - Adds disabled=disabled attribute
162    */
163    disableFormElements: function(form) {
164      form.find(rails.disableSelector).each(function() {
165        var element = $(this), method = element.is('button') ? 'html' : 'val';
166        element.data('ujs:enable-with', element[method]());
167        element[method](element.data('disable-with'));
168        element.attr('disabled', 'disabled');
169      });
170    },
171
172    /* Re-enables disabled form elements:
173      - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`)
174      - Removes disabled attribute
175    */
176    enableFormElements: function(form) {
177      form.find(rails.enableSelector).each(function() {
178        var element = $(this), method = element.is('button') ? 'html' : 'val';
179        if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with'));
180        element.removeAttr('disabled');
181      });
182    },
183
184   /* For 'data-confirm' attribute:
185      - Fires `confirm` event
186      - Shows the confirmation dialog
187      - Fires the `confirm:complete` event
188
189      Returns `true` if no function stops the chain and user chose yes; `false` otherwise.
190      Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog.
191      Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function
192      return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog.
193   */
194    allowAction: function(element) {
195      var message = element.data('confirm'),
196          answer = false, callback;
197      if (!message) { return true; }
198
199      if (rails.fire(element, 'confirm')) {
200        answer = rails.confirm(message);
201        callback = rails.fire(element, 'confirm:complete', [answer]);
202      }
203      return answer && callback;
204    },
205
206    // Helper function which checks for blank inputs in a form that match the specified CSS selector
207    blankInputs: function(form, specifiedSelector, nonBlank) {
208      var inputs = $(), input,
209        selector = specifiedSelector || 'input,textarea';
210      form.find(selector).each(function() {
211        input = $(this);
212        // Collect non-blank inputs if nonBlank option is true, otherwise, collect blank inputs
213        if (nonBlank ? input.val() : !input.val()) {
214          inputs = inputs.add(input);
215        }
216      });
217      return inputs.length ? inputs : false;
218    },
219
220    // Helper function which checks for non-blank inputs in a form that match the specified CSS selector
221    nonBlankInputs: function(form, specifiedSelector) {
222      return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank
223    },
224
225    // Helper function, needed to provide consistent behavior in IE
226    stopEverything: function(e) {
227      $(e.target).trigger('ujs:everythingStopped');
228      e.stopImmediatePropagation();
229      return false;
230    },
231
232    // find all the submit events directly bound to the form and
233    // manually invoke them. If anyone returns false then stop the loop
234    callFormSubmitBindings: function(form) {
235      var events = form.data('events'), continuePropagation = true;
236      if (events !== undefined && events['submit'] !== undefined) {
237        $.each(events['submit'], function(i, obj){
238          if (typeof obj.handler === 'function') return continuePropagation = obj.handler(obj.data);
239        });
240      }
241      return continuePropagation;
242    }
243  };
244
245  // ajaxPrefilter is a jQuery 1.5 feature
246  if ('ajaxPrefilter' in $) {
247    $.ajaxPrefilter(function(options, originalOptions, xhr){ rails.CSRFProtection(xhr); });
248  } else {
249    $(document).ajaxSend(function(e, xhr){ rails.CSRFProtection(xhr); });
250  }
251
252  $(rails.linkClickSelector).live('click.rails', function(e) {
253    var link = $(this);
254    if (!rails.allowAction(link)) return rails.stopEverything(e);
255
256    if (link.data('remote') !== undefined) {
257      rails.handleRemote(link);
258      return false;
259    } else if (link.data('method')) {
260      rails.handleMethod(link);
261      return false;
262    }
263  });
264
265  $(rails.formSubmitSelector).live('submit.rails', function(e) {
266    var form = $(this),
267      remote = form.data('remote') !== undefined,
268      blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector),
269      nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
270
271    if (!rails.allowAction(form)) return rails.stopEverything(e);
272
273    // skip other logic when required values are missing or file upload is present
274    if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
275      return rails.stopEverything(e);
276    }
277
278    if (remote) {
279      if (nonBlankFileInputs) {
280        return rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]);
281      }
282
283      // If browser does not support submit bubbling, then this live-binding will be called before direct
284      // bindings. Therefore, we should directly call any direct bindings before remotely submitting form.
285      if (!$.support.submitBubbles && rails.callFormSubmitBindings(form) === false) return rails.stopEverything(e);
286
287      rails.handleRemote(form);
288      return false;
289    } else {
290      // slight timeout so that the submit button gets properly serialized
291      setTimeout(function(){ rails.disableFormElements(form); }, 13);
292    }
293  });
294
295  $(rails.formInputClickSelector).live('click.rails', function(event) {
296    var button = $(this);
297
298    if (!rails.allowAction(button)) return rails.stopEverything(event);
299
300    // register the pressed submit button
301    var name = button.attr('name'),
302      data = name ? {name:name, value:button.val()} : null;
303
304    button.closest('form').data('ujs:submit-button', data);
305  });
306
307  $(rails.formSubmitSelector).live('ajax:beforeSend.rails', function(event) {
308    if (this == event.target) rails.disableFormElements($(this));
309  });
310
311  $(rails.formSubmitSelector).live('ajax:complete.rails', function(event) {
312    if (this == event.target) rails.enableFormElements($(this));
313  });
314
315})( jQuery );

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.