提交 9ef4b70b 编写于 作者: S Santiago Pastorino

Update jquery-ujs and prototype-ujs

上级 50762641
...@@ -3,151 +3,287 @@ ...@@ -3,151 +3,287 @@
* *
* Requires jQuery 1.4.3 or later. * Requires jQuery 1.4.3 or later.
* https://github.com/rails/jquery-ujs * https://github.com/rails/jquery-ujs
* Uploading file using rails.js
* =============================
*
* By default, browsers do not allow files to be uploaded via AJAX. As a result, if there are any non-blank file fields
* in the remote form, this adapter aborts the AJAX submission and allows the form to submit through standard means.
*
* The `ajax:aborted:file` event allows you to bind your own handler to process the form submission however you wish.
*
* Ex:
* $('form').live('ajax:aborted:file', function(event, elements){
* // Implement own remote file-transfer handler here for non-blank file inputs passed in `elements`.
* // Returning false in this handler tells rails.js to disallow standard form submission
* return false;
* });
*
* The `ajax:aborted:file` event is fired when a file-type input is detected with a non-blank value.
*
* Third-party tools can use this hook to detect when an AJAX file upload is attempted, and then use
* techniques like the iframe method to upload the file instead.
*
* Required fields in rails.js
* ===========================
*
* If any blank required inputs (required="required") are detected in the remote form, the whole form submission
* is canceled. Note that this is unlike file inputs, which still allow standard (non-AJAX) form submission.
*
* The `ajax:aborted:required` event allows you to bind your own handler to inform the user of blank required inputs.
*
* !! Note that Opera does not fire the form's submit event if there are blank required inputs, so this event may never
* get fired in Opera. This event is what causes other browsers to exhibit the same submit-aborting behavior.
*
* Ex:
* $('form').live('ajax:aborted:required', function(event, elements){
* // Returning false in this handler tells rails.js to submit the form anyway.
* // The blank required inputs are passed to this function in `elements`.
* return ! confirm("Would you like to submit the form with missing info?");
* });
*/ */
(function($) { (function($) {
// Triggers an event on an element and returns the event result // Shorthand to make it a little easier to call public rails functions from within rails.js
function fire(obj, name, data) { var rails;
var event = new $.Event(name);
obj.trigger(event, data); $.rails = rails = {
return event.result !== false; // Link elements bound by jquery-ujs
} linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]',
// Submits "remote" forms and links with ajax // Form elements bound by jquery-ujs
function handleRemote(element) { formSubmitSelector: 'form',
var method, url, data,
dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType); // Form input elements bound by jquery-ujs
formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])',
if (element.is('form')) {
method = element.attr('method'); // Form input elements disabled during form submission
url = element.attr('action'); disableSelector: 'input[data-disable-with], button[data-disable-with], textarea[data-disable-with]',
data = element.serializeArray();
// memoized value from clicked submit button // Form input elements re-enabled after form submission
var button = element.data('ujs:submit-button'); enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled',
if (button) {
data.push(button); // Form required input elements
element.data('ujs:submit-button', null); requiredInputSelector: 'input[name][required],textarea[name][required]',
}
} else { // Form file input elements
method = element.attr('data-method'); fileInputSelector: 'input:file',
url = element.attr('href');
// Make sure that every Ajax request sends the CSRF token
csrf_token = $('meta[name=csrf-token]').attr('content'); CSRFProtection: function(xhr) {
csrf_param = $('meta[name=csrf-param]').attr('content'); var token = $('meta[name="csrf-token"]').attr('content');
if (token) xhr.setRequestHeader('X-CSRF-Token', token);
data = {}; },
data[csrf_param] = csrf_token;
} // Triggers an event on an element and returns false if the event result is false
fire: function(obj, name, data) {
$.ajax({ var event = $.Event(name);
url: url, type: method || 'GET', data: data, dataType: dataType, obj.trigger(event, data);
// stopping the "ajax:beforeSend" event will cancel the ajax request return event.result !== false;
beforeSend: function(xhr, settings) { },
if (settings.dataType === undefined) {
xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script); // Submits "remote" forms and links with ajax
} handleRemote: function(element) {
return fire(element, 'ajax:beforeSend', [xhr, settings]); var method, url, data,
}, dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType);
success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]); if (rails.fire(element, 'ajax:before')) {
},
complete: function(xhr, status) { if (element.is('form')) {
element.trigger('ajax:complete', [xhr, status]); method = element.attr('method');
}, url = element.attr('action');
error: function(xhr, status, error) { data = element.serializeArray();
element.trigger('ajax:error', [xhr, status, error]); // memoized value from clicked submit button
} var button = element.data('ujs:submit-button');
}); if (button) {
} data.push(button);
element.data('ujs:submit-button', null);
// Handles "data-method" on links such as: }
// <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a> } else {
function handleMethod(link) { method = element.data('method');
var href = link.attr('href'), url = element.attr('href');
method = link.attr('data-method'), data = null;
csrf_token = $('meta[name=csrf-token]').attr('content'), }
csrf_param = $('meta[name=csrf-param]').attr('content'),
form = $('<form method="post" action="' + href + '"></form>'), $.ajax({
metadata_input = '<input name="_method" value="' + method + '" type="hidden" />'; url: url, type: method || 'GET', data: data, dataType: dataType,
// stopping the "ajax:beforeSend" event will cancel the ajax request
if (csrf_param !== undefined && csrf_token !== undefined) { beforeSend: function(xhr, settings) {
metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />'; if (settings.dataType === undefined) {
} xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
}
form.hide().append(metadata_input).appendTo('body'); return rails.fire(element, 'ajax:beforeSend', [xhr, settings]);
form.submit(); },
} success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]);
function disableFormElements(form) { },
form.find('input[data-disable-with]').each(function() { complete: function(xhr, status) {
var input = $(this); element.trigger('ajax:complete', [xhr, status]);
input.data('ujs:enable-with', input.val()) },
.val(input.attr('data-disable-with')) error: function(xhr, status, error) {
.attr('disabled', 'disabled'); element.trigger('ajax:error', [xhr, status, error]);
}); }
} });
}
function enableFormElements(form) { },
form.find('input[data-disable-with]').each(function() {
var input = $(this); // Handles "data-method" on links such as:
input.val(input.data('ujs:enable-with')).removeAttr('disabled'); // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
}); handleMethod: function(link) {
} var href = link.attr('href'),
method = link.data('method'),
function allowAction(element) { csrf_token = $('meta[name=csrf-token]').attr('content'),
var message = element.attr('data-confirm'); csrf_param = $('meta[name=csrf-param]').attr('content'),
return !message || (fire(element, 'confirm') && confirm(message)); form = $('<form method="post" action="' + href + '"></form>'),
} metadata_input = '<input name="_method" value="' + method + '" type="hidden" />';
function requiredValuesMissing(form) { if (csrf_param !== undefined && csrf_token !== undefined) {
var missing = false; metadata_input += '<input name="' + csrf_param + '" value="' + csrf_token + '" type="hidden" />';
form.find('input[name][required]').each(function() { }
if (!$(this).val()) missing = true;
}); form.hide().append(metadata_input).appendTo('body');
return missing; form.submit();
} },
$('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) { /* Disables form elements:
var link = $(this); - Caches element value in 'ujs:enable-with' data store
if (!allowAction(link)) return false; - Replaces element text with value of 'data-disable-with' attribute
- Adds disabled=disabled attribute
if (link.attr('data-remote') != undefined) { */
handleRemote(link); disableFormElements: function(form) {
return false; form.find(rails.disableSelector).each(function() {
} else if (link.attr('data-method')) { var element = $(this), method = element.is('button') ? 'html' : 'val';
handleMethod(link); element.data('ujs:enable-with', element[method]());
return false; element[method](element.data('disable-with'));
} element.attr('disabled', 'disabled');
}); });
},
$('form').live('submit.rails', function(e) {
var form = $(this), remote = form.attr('data-remote') != undefined; /* Re-enables disabled form elements:
if (!allowAction(form)) return false; - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`)
- Removes disabled attribute
// skip other logic when required values are missing */
if (requiredValuesMissing(form)) return !remote; enableFormElements: function(form) {
form.find(rails.enableSelector).each(function() {
if (remote) { var element = $(this), method = element.is('button') ? 'html' : 'val';
handleRemote(form); if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with'));
return false; element.removeAttr('disabled');
} else { });
disableFormElements(form); },
}
}); // If message provided in 'data-confirm' attribute, fires `confirm` event and returns result of confirm dialog.
// Attaching a handler to the element's `confirm` event that returns false cancels the confirm dialog.
$('form input[type=submit], form button[type=submit], form button:not([type])').live('click.rails', function() { allowAction: function(element) {
var button = $(this); var message = element.data('confirm');
if (!allowAction(button)) return false; return !message || (rails.fire(element, 'confirm') && confirm(message));
// register the pressed submit button },
var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null;
button.closest('form').data('ujs:submit-button', data); // Helper function which checks for blank inputs in a form that match the specified CSS selector
}); blankInputs: function(form, specifiedSelector, nonBlank) {
var inputs = $(), input,
$('form').live('ajax:beforeSend.rails', function(event) { selector = specifiedSelector || 'input,textarea';
if (this == event.target) disableFormElements($(this)); form.find(selector).each(function() {
}); input = $(this);
// Collect non-blank inputs if nonBlank option is true, otherwise, collect blank inputs
$('form').live('ajax:complete.rails', function(event) { if (nonBlank ? input.val() : !input.val()) {
if (this == event.target) enableFormElements($(this)); inputs = inputs.add(input);
}); }
});
return inputs.length ? inputs : false;
},
// Helper function which checks for non-blank inputs in a form that match the specified CSS selector
nonBlankInputs: function(form, specifiedSelector) {
return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank
},
// Helper function, needed to provide consistent behavior in IE
stopEverything: function(e) {
e.stopImmediatePropagation();
return false;
},
// find all the submit events directly bound to the form and
// manually invoke them. If anyone returns false then stop the loop
callFormSubmitBindings: function(form) {
var events = form.data('events'), continuePropagation = true;
if (events !== undefined && events['submit'] !== undefined) {
$.each(events['submit'], function(i, obj){
if (typeof obj.handler === 'function') return continuePropagation = obj.handler(obj.data);
});
}
return continuePropagation;
}
};
// ajaxPrefilter is a jQuery 1.5 feature
if ('ajaxPrefilter' in $) {
$.ajaxPrefilter(function(options, originalOptions, xhr){ rails.CSRFProtection(xhr); });
} else {
$(document).ajaxSend(function(e, xhr){ rails.CSRFProtection(xhr); });
}
$(rails.linkClickSelector).live('click.rails', function(e) {
var link = $(this);
if (!rails.allowAction(link)) return rails.stopEverything(e);
if (link.data('remote') !== undefined) {
rails.handleRemote(link);
return false;
} else if (link.data('method')) {
rails.handleMethod(link);
return false;
}
});
$(rails.formSubmitSelector).live('submit.rails', function(e) {
var form = $(this),
remote = form.data('remote') !== undefined,
blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector),
nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
if (!rails.allowAction(form)) return rails.stopEverything(e);
// skip other logic when required values are missing or file upload is present
if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
return !remote;
}
if (remote) {
if (nonBlankFileInputs) {
return rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]);
}
// If browser does not support submit bubbling, then this live-binding will be called before direct
// bindings. Therefore, we should directly call any direct bindings before remotely submitting form.
if (!$.support.submitBubbles && rails.callFormSubmitBindings(form) === false) return rails.stopEverything(e);
rails.handleRemote(form);
return false;
} else {
// slight timeout so that the submit button gets properly serialized
setTimeout(function(){ rails.disableFormElements(form); }, 13);
}
});
$(rails.formInputClickSelector).live('click.rails', function(event) {
var button = $(this);
if (!rails.allowAction(button)) return rails.stopEverything(event);
// register the pressed submit button
var name = button.attr('name'),
data = name ? {name:name, value:button.val()} : null;
button.closest('form').data('ujs:submit-button', data);
});
$(rails.formSubmitSelector).live('ajax:beforeSend.rails', function(event) {
if (this == event.target) rails.disableFormElements($(this));
});
$(rails.formSubmitSelector).live('ajax:complete.rails', function(event) {
if (this == event.target) rails.enableFormElements($(this));
});
})( jQuery ); })( jQuery );
(function() { (function() {
Ajax.Responders.register({
onCreate: function(request) {
var token = $$('meta[name=csrf-token]')[0];
if (token) {
if (!request.options.requestHeaders) request.options.requestHeaders = {};
request.options.requestHeaders['X-CSRF-Token'] = token.readAttribute('content');
}
}
});
// Technique from Juriy Zaytsev // Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) { function isEventSupported(eventName) {
...@@ -189,20 +199,4 @@ ...@@ -189,20 +199,4 @@
document.on('ajax:complete', 'form', function(event, form) { document.on('ajax:complete', 'form', function(event, form) {
if (form == event.findElement()) enableFormElements(form); if (form == event.findElement()) enableFormElements(form);
}); });
Ajax.Responders.register({
onCreate: function(request) {
var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
if (csrf_meta_tag) {
var header = 'X-CSRF-Token',
token = csrf_meta_tag.readAttribute('content');
if (!request.options.requestHeaders) {
request.options.requestHeaders = {};
}
request.options.requestHeaders[header] = token;
}
}
});
})(); })();
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册