简体   繁体   中英

How to override a JavaScript function in twitter bootstrap

We currently use Twitter Bootstrap 2.3.2 and I am trying to figure out a way to tie into the toggle function that is part of the dropdown component. I am trying to do this globally and have come up with this code:

; (function ($, window, document, undefined)
{
    var oldToggle = $.fn.dropdown.Constructor.prototype.toggle;

    $.fn.dropdown.Constructor.prototype.toggle = function (e)
        {
            console.log('here');
            return oldToggle.call(this, e);
        }
})(jQuery, window, document);

When I put this code in the bootstrap file, the override works fine. When I try to include it elsewhere on the page my console.log never executes. What am I missing here?

Here is a link to a JSFiddle that includes the code posted above http://jsfiddle.net/whoiskb/8nvuk/1/

You won't be able to overwrite that function from outside. Look at the bootstrap source

$(document)
    .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)

as soon as this event is bound, any change to the prototype won't take effect, because the original function was passed and you can't take this back.

https://github.com/twbs/bootstrap/blob/master/js/dropdown.js#L141

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM