How to Extend Twitter Bootstrap Plugin

后端 未结 5 1913
面向向阳花
面向向阳花 2020-11-27 02:43

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 exa

5条回答
  •  孤城傲影
    2020-11-27 03:33

    +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);
    

提交回复
热议问题