Search code examples
javascriptjquerytwitter-bootstrapmodal-dialogextend

Extending bootstrap jQuery modal


I would like to extend $.fn.modal in Bootstrap/jQuery so my extended version "does things" before a modal is initialized by passing extra options. I tried this like I do some times to extend jQuery prototypes:

var modal = $.fn.modal;

$.fn.modal = function() {
    this.each(function() {
        // do stuff
    });
    modal.apply(this, arguments);
}

$('#modal').modal(); // fails

The example above does not work, although the same pattern works for many other non-bootstrap jQuery prototypes.

Here’s a fiddle that demonstrates it: http://jsfiddle.net/eTWSb/ (just comment the override stuff to see it working).

I was under the impression that cloning a function and then calling it as a "super" is a viable option when you want to add custom functionality.

Any suggestions?


Solution

  • OK I figured it out. When overriding $.fn.modal I’m also removing the default options that bootstrap placed in $.fn.modal.defaults (why?).

    So when I extended it, I lost the default show: true option that actually shows the modal...

    This solves it (but the constructor is lost unless you copy that too):

    var modal = $.fn.modal,
        defaults = $.extend({}, $.fn.modal.defaults);
    
    $.fn.modal = function(options) {
        options = $.extend( defaults, options );
        this.each(function() {
            // do stuff
        });
        return modal.call( this, options );
    };