Skip to content

Instantly share code, notes, and snippets.

@bradgreens
Created January 22, 2014 17:13
Show Gist options
  • Save bradgreens/8562834 to your computer and use it in GitHub Desktop.
Save bradgreens/8562834 to your computer and use it in GitHub Desktop.
Rails jQuery UJS-esque click event method actions.
/*
** jQuery Plugin Pattern
* http://jqueryboilerplate.com/
*/
!function( $, undefined ) {
var pluginName = 'railsMethodActions',
defaults = {
selector: '[data-method]'
}
function Plugin(element, options) {
this.options = $.extend({}, defaults, options)
this._name = pluginName
this.$element = $( element ).find( this.options.selector )
this.init()
} // end Plugin()
Plugin.prototype = {
init: function() {
this.$element.on( this.addNs('click'), this.handleMethod.bind( this ))
},
handleMethod: function(event) {
var url, method
if( event.isDefaultPrevented() ) return
event.preventDefault()
url = this.$element.attr('href')
method = this.$element.data('method')
$.ajax({
url: url,
type: 'post',
dataType: "json",
data: { "_method" : method }
})
.done( this.done.bind( this ) )
.fail( this.fail.bind( this ) )
},
done: function(response) {
location.href = response.redirect_location
},
fail: function(response) {
alert('There was an error completing the action. Please contact your system administrator for assistance.')
},
addNs: function(event) {
return event + '.' + pluginName
}
}
$.fn[ pluginName ] = function( options ) {
return this.each(function() {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName, new Plugin(this, options))
}
})
}
}( jQuery )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment