Created
June 18, 2013 11:21
-
-
Save anonymous/5804591 to your computer and use it in GitHub Desktop.
jQuery extending/overriding a (Twitter Bootstrap) plugin method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This way you can | |
* 1) add your own default options | |
* 2) create new methods with custom arguments and access to original (super) functions | |
* 3) do stuff in the constructor before and/or after the original constructor is called | |
* | |
* Source: http://stackoverflow.com/a/12689534/440643 | |
*/ | |
// save the original function object | |
var _super = $.fn.modal; | |
// add custom defaults | |
$.extend( _super.defaults, { | |
foo: 'bar', | |
john: 'doe' | |
}); | |
// create a new constructor | |
var Modal = function(element, options) { | |
// do custom constructor stuff here | |
// call the original constructor | |
_super.Constructor.apply( this, arguments ); | |
} | |
// extend prototypes and add a super function | |
Modal.prototype = $.extend({}, _super.Constructor.prototype, { | |
constructor: Modal, | |
_super: function() { | |
var args = $.makeArray(arguments); | |
_super.Constructor.prototype[args.shift()].apply(this, args); | |
}, | |
show: function() { | |
// do custom method stuff | |
// call the original method | |
this._super('show'); | |
} | |
}); | |
// override the old initialization with the new constructor | |
$.fn.modal = $.extend(function(option) { | |
var args = $.makeArray(arguments), | |
option = args.shift(); | |
return this.each(function() { | |
var $this = $(this); | |
var data = $this.data('modal'), | |
options = $.extend({}, _super.defaults, $this.data(), typeof option == 'object' && option); | |
if ( !data ) { | |
$this.data('modal', (data = new Modal(this, options))); | |
} | |
if (typeof option == 'string') { | |
data[option].apply( data, args ); | |
} | |
else if ( options.show ) { | |
data.show.apply( data, args ); | |
} | |
}); | |
}, $.fn.modal); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source: http://stackoverflow.com/a/14823315/440643 | |
var _show = $.fn.modal.Constructor.prototype.show; | |
$.fn.modal.Constructor.prototype.show = function() { | |
_show.apply(this, arguments); | |
//Do custom stuff here | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment