Skip to content

Instantly share code, notes, and snippets.

@carlosvini
Created February 6, 2017 15:17
Show Gist options
  • Save carlosvini/4f4e0aa1340d01022d921267a41c1ffa to your computer and use it in GitHub Desktop.
Save carlosvini/4f4e0aa1340d01022d921267a41c1ffa to your computer and use it in GitHub Desktop.
/**
* Inserts the response content into a target element.
*
* data-once Load ajax only once
* data-target #id of the target div
* data-remote true (Rais UJS properties)
*/
$(document).on('ajax:success', '[data-target]', function(e, data, status, xhr) {
if (this !== e.target) {
return; // prevent propagation to parent nodes
}
var target = $(this).data('target');
if (!$(target).length && target[0] == '#') {
// Create target if it doesn't exist
$('body').append('<div id="' + target.substring(1) + '"></div>');
}
// Avoid losing called element, otherwise ajax:complete won't be called
if ($(this).parents(target).length) {
$(this).appendTo('body')
.addClass('pending-ajax-complete')
.hide();
}
// Persist the target to new ajax links
$(target).html(data)
.find('[data-remote]:not([data-target])')
.attr('data-target', target);
if ($(this).data('once')) {
$(this).data('disabled', true);
}
});
$(document).on('ajax:before', '[data-target]', function(e) {
if ($(this).data('disabled')) {
e.stopImmediatePropagation();
return false;
}
});
// Generic decoration
$(document).on('ajax:before', '[data-remote]', function() {
$('body').addClass('ajax-loading');
});
$(document).on('ajax:complete', '[data-remote]', function() {
$('body').removeClass('ajax-loading');
if ($(this).is('.pending-ajax-complete')) {
$(this).remove();
}
});
// Fancybox trigger
/*
$(document).on('ajax:success', '[data-toggle=fancybox]', function(xhr, data, status) {
var target = $(this).data('target');
require(['fancybox'], function() {
$.fancybox(target, {
wrapCSS: target.substring(1) + '-modal' // allows custom style
});
});
});
*/
// Append content from ajax
/*
$(document).on('ajax:success', '[data-append-to]', function(xhr, data, status) {
var appendTo = $(this).data('append-to');
$(appendTo).append(data);
// Handle data-params
if ($(this).data('params')) {
var paramsObj = deparam($(this).data('params'));
if (paramsObj.page) {
paramsObj.page++; // Paginate
}
$(this).data('params', $.param(paramsObj));
}
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment