45

I am digging into Twitter's Bootstrap and now want to try and add some functionality to the plugins, but I can't figure out how to do so. Using the modal plugin as an example (http://twitter.github.com/bootstrap/javascript.html#modals), I'd like to add a new function to the plugin that can be called as one would the standard plugin methods. THe closest I think I have come is with the following code, but all I get when I try to access is that the function is not part of the object.

Any suggestions? This is what I have tried that seems to be the closest to what I need to do:

 $.extend($.fn.modal, { 
    showFooterMessage: function (message) { 
        alert("Hey"); 
    } 
}); 

Then I would want to call it as follows:

  $(this).closest(".modal").modal("showFooterMessage"); 

EDIT: OK, I figured out how to do this:

(function ($) {
    var extensionMethods = {
        displayFooterMessage: function ($msg) {
            var args = arguments[0]
            var that = this;

            // do stuff here
        }
    }

    $.extend(true, $.fn.modal.Constructor.prototype, extensionMethods);
})(jQuery);

The problem with the existing set of Bootstrap plugins is that if anyone wants to extend them, none of the new methods can accept arguments. My attempt to "fix" this was to add the acceptance of arguments in the plugins function call.

$.fn.modal = function (option) {
    var args = arguments[1] || {};
    return this.each(function () {
        var $this = $(this)
        , data = $this.data('modal')
        , options = typeof option == 'object' && option

        if (!data) $this.data('modal', (data = new Modal(this, options)))

        if (typeof option == 'string') data[option](args)
        else data.show()

    }) // end each
} // end $.fn.modal
Zain Shaikh
  • 6,013
  • 6
  • 41
  • 66
AlexGad
  • 6,612
  • 5
  • 33
  • 45
  • 5
    If this edit was meant to be an answer, you should be able to post it as an answer now. Please go ahead and do so :) – BoltClock Mar 16 '12 at 19:05
  • Seemed kinda lame to answer my own question ;) – AlexGad Apr 04 '12 at 18:59
  • 1
    Oh, don't worry. It's perfectly normal - even [I've done it once](http://stackoverflow.com/questions/5493149/how-do-i-make-a-wpf-window-movable-by-dragging-the-extended-glass-frame) :) – BoltClock Apr 04 '12 at 19:04

5 Answers5

37

This is an old thread, but I just made some custom extensions to modal using the following pattern:

// 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 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

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • David - I'd be grateful if you could take a look at my question about the overriding initialization syntax you used: http://stackoverflow.com/q/39751235 – Arek Dygas Sep 29 '16 at 11:22
  • do you have a similar solution with Bootstrap 4? – Steven Jul 25 '19 at 19:22
29

For the record there is a simple method to override or extend existing functions:

var _show = $.fn.modal.Constructor.prototype.show;

$.fn.modal.Constructor.prototype.show = function() {
    _show.apply(this, arguments);
    //Do custom stuff here
};

Doesn't cover custom arguments, but it's easy as well with the method above; instead of using apply and arguments, specify the original arguments plus the custom ones in the function definition, then call the original _show (or whichever it is) with the original arguments, and finally do other stuff with the new arguments.

Mahn
  • 16,261
  • 16
  • 62
  • 78
  • Somehow the other methods would run into an infinite loop each time.. this one works perfect! +1 for simplicity :) – Björn Jun 18 '13 at 11:17
  • This is great, but not good if you want to extend the constructor (do things on construction, such as add bindings/etc.). – prograhammer Jul 06 '15 at 15:45
  • 1
    @DavidGraham you can override the constructor too, it's right there in the prototype. In the above example you'd want to override the `$.fn.modal.Constructor.prototype.constructor` method. – Mahn Jul 06 '15 at 17:06
4

For reference, I had a similar problem so I "extended" the Typeahead plugin by forking and adding the functionality I needed in the plugin script itself.

If you have to change the source it's not really an extension anyways so I figured it was easier just to put all my modifications in one place.

Terry
  • 14,099
  • 9
  • 56
  • 84
2

For anyone looking to do this with Bootstrap 3. The plugin layout has changed a bit the default options for all Bootstrap 3 plugins are attached to the plugins constructor:

var _super = $.fn.modal;
$.extend(_super.Constructor.DEFAULTS, {
       foo: 'bar',
       john: 'doe'
});
Phil Nicholas
  • 3,681
  • 1
  • 19
  • 23
benembery
  • 666
  • 7
  • 20
2

+1 for the accepted answer above from David. But if I could simplify it a bit more, I'd adjust the DEFAULTS extending and $fn.modal extending like so:

!function($) {

    'use strict';

    // save the original function object
    var _super = $.fn.modal;

    // create a new constructor
    var Modal = function(element, options) {

        // do custom constructor stuff here

        // call the original constructor
        _super.Constructor.apply( this, arguments );

    }

    // add custom defaults
    Modal.DEFAULTS = $.extend( _super.defaults, {
         myCustomOption: true
    });

    // 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');
        },
        myCustomMethod: function() {
            alert('new feature!');
        }
    });

    // Copied exactly from Bootstrap 3 (as of Modal.VERSION  = '3.3.5')
    // Notice: You can copy & paste it exactly, no differences!
    function Plugin(option, _relatedTarget) {
        return this.each(function () {
            var $this   = $(this)
            var data    = $this.data('bs.modal')
            var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)

            if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
            if (typeof option == 'string') data[option](_relatedTarget)
            else if (options.show) data.show(_relatedTarget)
        })
    }

    // override the old initialization with the new constructor
    $.fn.modal = $.extend(Plugin, $.fn.modal);

}(jQuery);
prograhammer
  • 20,132
  • 13
  • 91
  • 118
  • As suggested by @benembery, default options are attached to the Constructor namespace. For this solution, I think custom defaults needs to be // add custom defaults Modal.DEFAULTS = $.extend( _super.Constructor.DEFAULTS, { myCustomOption: true }); – jakxnz Jul 25 '16 at 05:05