Skip to content

Instantly share code, notes, and snippets.

@19WAS85
Last active December 29, 2015 13:09
Show Gist options
  • Save 19WAS85/7674918 to your computer and use it in GitHub Desktop.
Save 19WAS85/7674918 to your computer and use it in GitHub Desktop.
jquery data-async attribute support
$(function () {
$('*[data-async="true"]').each(function () {
var self = $(this);
if (self.data('handled') != null) return;
var events = self.data('events') || 'click';
self.bind(events, function (e) {
var preventDefault = self.data('prevent-default');
if (preventDefault == 'true') e.preventDefault();
var confirmMessage = self.data('confirm');
if (confirmMessage != null && !confirm(confirmMessage)) return;
var params = {};
params.method = self.data('method') || 'post';
params.url = self.data('url');
params.cache = self.data('cache');
params.success = function (data) {
var target = self.data('target');
if (target != null) $('#' + target).html(data);
var callback = self.data('callback');
if (callback != null) window[callback](data);
}
var asyncData = self.data('parameters');
if (asyncData != null) {
var evalFunction = "(function(self) { return "+ asyncData +" })";
params.data = eval(evalFunction)(self);
}
$.ajax(params);
});
self.attr('data-handled', 'true');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment