0

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/

4
  • 2
    you need to add it after the bootstrap.js file... also, does the console show any errors? Commented Feb 27, 2014 at 15:24
  • When I include the script, it is included after the bootstrap file. The console does not show any errors. Commented Feb 27, 2014 at 15:28
  • 1
    I'm not that familiar with how Bootstrap works, but is it possible that this is happening?: 1) Bootstrap code runs 2) "Toggle" event handlers are attached to elements on the page 3) Your code overrides Bootstrap function in dropdown prototype, but is now too late. Commented Feb 27, 2014 at 15:59
  • @Zhihao good guess. I was just posting this as an answer. Commented Feb 27, 2014 at 16:00

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

That does make sense, I did over look that. I now tried to see if I could rebind the event but that doesn't seem to be working. Shouldn't I be able to remove the existing event with $(document).off('click.bs.dropdown.data-api')
It should be $(document).off('click.bs.dropdown.data-api', '[data-toggle=dropdown]'), but for some reason that doesn't work in your fiddle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.