Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// uses https://github.com/rails/jquery-ujs
var RemoteEvents = {
events: {
'post': 'submit',
'put': 'submit',
'delete': 'destroy'
},
errors: {
422: 'validationError',
404: 'notFound'
},
start: function($, root){
$.ajaxPrefilter(function(options, originalOptions, xhr) {
xhr.method = options.type.toLowerCase();
});
var self = this;
$(root).bind({
'ajax:success': function(e, data, status, xhr) {
var eventName = self.events[xhr.method];
eventName && $(e.target).trigger('remote:' + eventName, [data, status, xhr]);
},
'ajax:error': function(e, xhr) {
var errorName = self.errors[xhr.status];
errorName && $(e.target).trigger('remote:' + errorName, [xhr.responseText, xhr.status, xhr]);
}
});
}
};
RemoteEvents.start($, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment