simple-jquery-rails 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,510 @@
1
+ (function($, undefined) {
2
+
3
+ /**
4
+ * Unobtrusive scripting adapter for jQuery
5
+ * https://github.com/rails/jquery-ujs
6
+ *
7
+ * Requires jQuery 1.8.0 or later.
8
+ *
9
+ * Released under the MIT license
10
+ *
11
+ */
12
+
13
+ // Cut down on the number of issues from people inadvertently including jquery_ujs twice
14
+ // by detecting and raising an error when it happens.
15
+ 'use strict';
16
+
17
+ if ( $.rails !== undefined ) {
18
+ $.error('jquery-ujs has already been loaded!');
19
+ }
20
+
21
+ // Shorthand to make it a little easier to call public rails functions from within rails.js
22
+ var rails;
23
+ var $document = $(document);
24
+
25
+ $.rails = rails = {
26
+ // Link elements bound by jquery-ujs
27
+ linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with], a[data-disable]',
28
+
29
+ // Button elements bound by jquery-ujs
30
+ buttonClickSelector: 'button[data-remote]:not(form button), button[data-confirm]:not(form button)',
31
+
32
+ // Select elements bound by jquery-ujs
33
+ inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',
34
+
35
+ // Form elements bound by jquery-ujs
36
+ formSubmitSelector: 'form',
37
+
38
+ // Form input elements bound by jquery-ujs
39
+ formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])',
40
+
41
+ // Form input elements disabled during form submission
42
+ disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled',
43
+
44
+ // Form input elements re-enabled after form submission
45
+ enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled',
46
+
47
+ // Form required input elements
48
+ requiredInputSelector: 'input[name][required]:not([disabled]),textarea[name][required]:not([disabled])',
49
+
50
+ // Form file input elements
51
+ fileInputSelector: 'input[type=file]:not([disabled])',
52
+
53
+ // Link onClick disable selector with possible reenable after remote submission
54
+ linkDisableSelector: 'a[data-disable-with], a[data-disable]',
55
+
56
+ // Button onClick disable selector with possible reenable after remote submission
57
+ buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]',
58
+
59
+ // Up-to-date Cross-Site Request Forgery token
60
+ csrfToken: function() {
61
+ return $('meta[name=csrf-token]').attr('content');
62
+ },
63
+
64
+ // URL param that must contain the CSRF token
65
+ csrfParam: function() {
66
+ return $('meta[name=csrf-param]').attr('content');
67
+ },
68
+
69
+ // Make sure that every Ajax request sends the CSRF token
70
+ CSRFProtection: function(xhr) {
71
+ var token = rails.csrfToken();
72
+ if (token) xhr.setRequestHeader('X-CSRF-Token', token);
73
+ },
74
+
75
+ // Make sure that all forms have actual up-to-date tokens (cached forms contain old ones)
76
+ refreshCSRFTokens: function(){
77
+ $('form input[name="' + rails.csrfParam() + '"]').val(rails.csrfToken());
78
+ },
79
+
80
+ // Triggers an event on an element and returns false if the event result is false
81
+ fire: function(obj, name, data) {
82
+ var event = $.Event(name);
83
+ obj.trigger(event, data);
84
+ return event.result !== false;
85
+ },
86
+
87
+ // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm
88
+ confirm: function(message) {
89
+ return confirm(message);
90
+ },
91
+
92
+ // Default ajax function, may be overridden with custom function in $.rails.ajax
93
+ ajax: function(options) {
94
+ return $.ajax(options);
95
+ },
96
+
97
+ // Default way to get an element's href. May be overridden at $.rails.href.
98
+ href: function(element) {
99
+ return element[0].href;
100
+ },
101
+
102
+ // Checks "data-remote" if true to handle the request through a XHR request.
103
+ isRemote: function(element) {
104
+ return element.data('remote') !== undefined && element.data('remote') !== false;
105
+ },
106
+
107
+ // Submits "remote" forms and links with ajax
108
+ handleRemote: function(element) {
109
+ var method, url, data, withCredentials, dataType, options;
110
+
111
+ if (rails.fire(element, 'ajax:before')) {
112
+ withCredentials = element.data('with-credentials') || null;
113
+ dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType);
114
+
115
+ if (element.is('form')) {
116
+ method = element.attr('method');
117
+ url = element.attr('action');
118
+ data = element.serializeArray();
119
+ // memoized value from clicked submit button
120
+ var button = element.data('ujs:submit-button');
121
+ if (button) {
122
+ data.push(button);
123
+ element.data('ujs:submit-button', null);
124
+ }
125
+ } else if (element.is(rails.inputChangeSelector)) {
126
+ method = element.data('method');
127
+ url = element.data('url');
128
+ data = element.serialize();
129
+ if (element.data('params')) data = data + '&' + element.data('params');
130
+ } else if (element.is(rails.buttonClickSelector)) {
131
+ method = element.data('method') || 'get';
132
+ url = element.data('url');
133
+ data = element.serialize();
134
+ if (element.data('params')) data = data + '&' + element.data('params');
135
+ } else {
136
+ method = element.data('method');
137
+ url = rails.href(element);
138
+ data = element.data('params') || null;
139
+ }
140
+
141
+ options = {
142
+ type: method || 'GET', data: data, dataType: dataType,
143
+ // stopping the "ajax:beforeSend" event will cancel the ajax request
144
+ beforeSend: function(xhr, settings) {
145
+ if (settings.dataType === undefined) {
146
+ xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
147
+ }
148
+ if (rails.fire(element, 'ajax:beforeSend', [xhr, settings])) {
149
+ element.trigger('ajax:send', xhr);
150
+ } else {
151
+ return false;
152
+ }
153
+ },
154
+ success: function(data, status, xhr) {
155
+ element.trigger('ajax:success', [data, status, xhr]);
156
+ },
157
+ complete: function(xhr, status) {
158
+ element.trigger('ajax:complete', [xhr, status]);
159
+ },
160
+ error: function(xhr, status, error) {
161
+ element.trigger('ajax:error', [xhr, status, error]);
162
+ },
163
+ crossDomain: rails.isCrossDomain(url)
164
+ };
165
+
166
+ // There is no withCredentials for IE6-8 when
167
+ // "Enable native XMLHTTP support" is disabled
168
+ if (withCredentials) {
169
+ options.xhrFields = {
170
+ withCredentials: withCredentials
171
+ };
172
+ }
173
+
174
+ // Only pass url to `ajax` options if not blank
175
+ if (url) { options.url = url; }
176
+
177
+ return rails.ajax(options);
178
+ } else {
179
+ return false;
180
+ }
181
+ },
182
+
183
+ // Determines if the request is a cross domain request.
184
+ isCrossDomain: function(url) {
185
+ var originAnchor = document.createElement('a');
186
+ originAnchor.href = location.href;
187
+ var urlAnchor = document.createElement('a');
188
+
189
+ try {
190
+ urlAnchor.href = url;
191
+ // This is a workaround to a IE bug.
192
+ urlAnchor.href = urlAnchor.href;
193
+
194
+ // If URL protocol is false or is a string containing a single colon
195
+ // *and* host are false, assume it is not a cross-domain request
196
+ // (should only be the case for IE7 and IE compatibility mode).
197
+ // Otherwise, evaluate protocol and host of the URL against the origin
198
+ // protocol and host.
199
+ return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') && !urlAnchor.host) ||
200
+ (originAnchor.protocol + '//' + originAnchor.host ===
201
+ urlAnchor.protocol + '//' + urlAnchor.host));
202
+ } catch (e) {
203
+ // If there is an error parsing the URL, assume it is crossDomain.
204
+ return true;
205
+ }
206
+ },
207
+
208
+ // Handles "data-method" on links such as:
209
+ // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
210
+ handleMethod: function(link) {
211
+ var href = rails.href(link),
212
+ method = link.data('method'),
213
+ target = link.attr('target'),
214
+ csrfToken = rails.csrfToken(),
215
+ csrfParam = rails.csrfParam(),
216
+ form = $('<form method="post" action="' + href + '"></form>'),
217
+ metadataInput = '<input name="_method" value="' + method + '" type="hidden" />';
218
+
219
+ if (csrfParam !== undefined && csrfToken !== undefined && !rails.isCrossDomain(href)) {
220
+ metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />';
221
+ }
222
+
223
+ if (target) { form.attr('target', target); }
224
+
225
+ form.hide().append(metadataInput).appendTo('body');
226
+ form.submit();
227
+ },
228
+
229
+ // Helper function that returns form elements that match the specified CSS selector
230
+ // If form is actually a "form" element this will return associated elements outside the from that have
231
+ // the html form attribute set
232
+ formElements: function(form, selector) {
233
+ return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector);
234
+ },
235
+
236
+ /* Disables form elements:
237
+ - Caches element value in 'ujs:enable-with' data store
238
+ - Replaces element text with value of 'data-disable-with' attribute
239
+ - Sets disabled property to true
240
+ */
241
+ disableFormElements: function(form) {
242
+ rails.formElements(form, rails.disableSelector).each(function() {
243
+ rails.disableFormElement($(this));
244
+ });
245
+ },
246
+
247
+ disableFormElement: function(element) {
248
+ var method, replacement;
249
+
250
+ method = element.is('button') ? 'html' : 'val';
251
+ replacement = element.data('disable-with');
252
+
253
+ element.data('ujs:enable-with', element[method]());
254
+ if (replacement !== undefined) {
255
+ element[method](replacement);
256
+ }
257
+
258
+ element.prop('disabled', true);
259
+ },
260
+
261
+ /* Re-enables disabled form elements:
262
+ - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`)
263
+ - Sets disabled property to false
264
+ */
265
+ enableFormElements: function(form) {
266
+ rails.formElements(form, rails.enableSelector).each(function() {
267
+ rails.enableFormElement($(this));
268
+ });
269
+ },
270
+
271
+ enableFormElement: function(element) {
272
+ var method = element.is('button') ? 'html' : 'val';
273
+ if (typeof element.data('ujs:enable-with') !== 'undefined') element[method](element.data('ujs:enable-with'));
274
+ element.prop('disabled', false);
275
+ },
276
+
277
+ /* For 'data-confirm' attribute:
278
+ - Fires `confirm` event
279
+ - Shows the confirmation dialog
280
+ - Fires the `confirm:complete` event
281
+
282
+ Returns `true` if no function stops the chain and user chose yes; `false` otherwise.
283
+ Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog.
284
+ Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function
285
+ return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog.
286
+ */
287
+ allowAction: function(element) {
288
+ var message = element.data('confirm'),
289
+ answer = false, callback;
290
+ if (!message) { return true; }
291
+
292
+ if (rails.fire(element, 'confirm')) {
293
+ try {
294
+ answer = rails.confirm(message);
295
+ } catch (e) {
296
+ (console.error || console.log).call(console, e.stack || e);
297
+ }
298
+ callback = rails.fire(element, 'confirm:complete', [answer]);
299
+ }
300
+ return answer && callback;
301
+ },
302
+
303
+ // Helper function which checks for blank inputs in a form that match the specified CSS selector
304
+ blankInputs: function(form, specifiedSelector, nonBlank) {
305
+ var inputs = $(), input, valueToCheck,
306
+ selector = specifiedSelector || 'input,textarea',
307
+ allInputs = form.find(selector);
308
+
309
+ allInputs.each(function() {
310
+ input = $(this);
311
+ valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : !!input.val();
312
+ if (valueToCheck === nonBlank) {
313
+
314
+ // Don't count unchecked required radio if other radio with same name is checked
315
+ if (input.is('input[type=radio]') && allInputs.filter('input[type=radio]:checked[name="' + input.attr('name') + '"]').length) {
316
+ return true; // Skip to next input
317
+ }
318
+
319
+ inputs = inputs.add(input);
320
+ }
321
+ });
322
+ return inputs.length ? inputs : false;
323
+ },
324
+
325
+ // Helper function which checks for non-blank inputs in a form that match the specified CSS selector
326
+ nonBlankInputs: function(form, specifiedSelector) {
327
+ return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank
328
+ },
329
+
330
+ // Helper function, needed to provide consistent behavior in IE
331
+ stopEverything: function(e) {
332
+ $(e.target).trigger('ujs:everythingStopped');
333
+ e.stopImmediatePropagation();
334
+ return false;
335
+ },
336
+
337
+ // Replace element's html with the 'data-disable-with' after storing original html
338
+ // and prevent clicking on it
339
+ disableElement: function(element) {
340
+ var replacement = element.data('disable-with');
341
+
342
+ element.data('ujs:enable-with', element.html()); // store enabled state
343
+ if (replacement !== undefined) {
344
+ element.html(replacement);
345
+ }
346
+
347
+ element.bind('click.railsDisable', function(e) { // prevent further clicking
348
+ return rails.stopEverything(e);
349
+ });
350
+ },
351
+
352
+ // Restore element to its original state which was disabled by 'disableElement' above
353
+ enableElement: function(element) {
354
+ if (element.data('ujs:enable-with') !== undefined) {
355
+ element.html(element.data('ujs:enable-with')); // set to old enabled state
356
+ element.removeData('ujs:enable-with'); // clean up cache
357
+ }
358
+ element.unbind('click.railsDisable'); // enable element
359
+ }
360
+ };
361
+
362
+ if (rails.fire($document, 'rails:attachBindings')) {
363
+
364
+ $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }});
365
+
366
+ // This event works the same as the load event, except that it fires every
367
+ // time the page is loaded.
368
+ //
369
+ // See https://github.com/rails/jquery-ujs/issues/357
370
+ // See https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching
371
+ $(window).on('pageshow.rails', function () {
372
+ $($.rails.enableSelector).each(function () {
373
+ var element = $(this);
374
+
375
+ if (element.data('ujs:enable-with')) {
376
+ $.rails.enableFormElement(element);
377
+ }
378
+ });
379
+
380
+ $($.rails.linkDisableSelector).each(function () {
381
+ var element = $(this);
382
+
383
+ if (element.data('ujs:enable-with')) {
384
+ $.rails.enableElement(element);
385
+ }
386
+ });
387
+ });
388
+
389
+ $document.delegate(rails.linkDisableSelector, 'ajax:complete', function() {
390
+ rails.enableElement($(this));
391
+ });
392
+
393
+ $document.delegate(rails.buttonDisableSelector, 'ajax:complete', function() {
394
+ rails.enableFormElement($(this));
395
+ });
396
+
397
+ $document.delegate(rails.linkClickSelector, 'click.rails', function(e) {
398
+ var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey;
399
+ if (!rails.allowAction(link)) return rails.stopEverything(e);
400
+
401
+ if (!metaClick && link.is(rails.linkDisableSelector)) rails.disableElement(link);
402
+
403
+ if (rails.isRemote(link)) {
404
+ if (metaClick && (!method || method === 'GET') && !data) { return true; }
405
+
406
+ var handleRemote = rails.handleRemote(link);
407
+ // Response from rails.handleRemote() will either be false or a deferred object promise.
408
+ if (handleRemote === false) {
409
+ rails.enableElement(link);
410
+ } else {
411
+ handleRemote.fail( function() { rails.enableElement(link); } );
412
+ }
413
+ return false;
414
+
415
+ } else if (method) {
416
+ rails.handleMethod(link);
417
+ return false;
418
+ }
419
+ });
420
+
421
+ $document.delegate(rails.buttonClickSelector, 'click.rails', function(e) {
422
+ var button = $(this);
423
+
424
+ if (!rails.allowAction(button) || !rails.isRemote(button)) return rails.stopEverything(e);
425
+
426
+ if (button.is(rails.buttonDisableSelector)) rails.disableFormElement(button);
427
+
428
+ var handleRemote = rails.handleRemote(button);
429
+ // Response from rails.handleRemote() will either be false or a deferred object promise.
430
+ if (handleRemote === false) {
431
+ rails.enableFormElement(button);
432
+ } else {
433
+ handleRemote.fail( function() { rails.enableFormElement(button); } );
434
+ }
435
+ return false;
436
+ });
437
+
438
+ $document.delegate(rails.inputChangeSelector, 'change.rails', function(e) {
439
+ var link = $(this);
440
+ if (!rails.allowAction(link) || !rails.isRemote(link)) return rails.stopEverything(e);
441
+
442
+ rails.handleRemote(link);
443
+ return false;
444
+ });
445
+
446
+ $document.delegate(rails.formSubmitSelector, 'submit.rails', function(e) {
447
+ var form = $(this),
448
+ remote = rails.isRemote(form),
449
+ blankRequiredInputs,
450
+ nonBlankFileInputs;
451
+
452
+ if (!rails.allowAction(form)) return rails.stopEverything(e);
453
+
454
+ // Skip other logic when required values are missing or file upload is present
455
+ if (form.attr('novalidate') === undefined) {
456
+ blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector, false);
457
+ if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
458
+ return rails.stopEverything(e);
459
+ }
460
+ }
461
+
462
+ if (remote) {
463
+ nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
464
+ if (nonBlankFileInputs) {
465
+ // Slight timeout so that the submit button gets properly serialized
466
+ // (make it easy for event handler to serialize form without disabled values)
467
+ setTimeout(function(){ rails.disableFormElements(form); }, 13);
468
+ var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]);
469
+
470
+ // Re-enable form elements if event bindings return false (canceling normal form submission)
471
+ if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); }
472
+
473
+ return aborted;
474
+ }
475
+
476
+ rails.handleRemote(form);
477
+ return false;
478
+
479
+ } else {
480
+ // Slight timeout so that the submit button gets properly serialized
481
+ setTimeout(function(){ rails.disableFormElements(form); }, 13);
482
+ }
483
+ });
484
+
485
+ $document.delegate(rails.formInputClickSelector, 'click.rails', function(event) {
486
+ var button = $(this);
487
+
488
+ if (!rails.allowAction(button)) return rails.stopEverything(event);
489
+
490
+ // Register the pressed submit button
491
+ var name = button.attr('name'),
492
+ data = name ? {name:name, value:button.val()} : null;
493
+
494
+ button.closest('form').data('ujs:submit-button', data);
495
+ });
496
+
497
+ $document.delegate(rails.formSubmitSelector, 'ajax:send.rails', function(event) {
498
+ if (this === event.target) rails.disableFormElements($(this));
499
+ });
500
+
501
+ $document.delegate(rails.formSubmitSelector, 'ajax:complete.rails', function(event) {
502
+ if (this === event.target) rails.enableFormElements($(this));
503
+ });
504
+
505
+ $(function(){
506
+ rails.refreshCSRFTokens();
507
+ });
508
+ }
509
+
510
+ })( jQuery );