Reputation: 23
Is it possible to use knockout to trigger the bootstrap dropdown function?
I've made a jsfiddle to highlight the problem:
This bit toggles the menu and makes is visible on load:
$('.dropdown-toggle').dropdown('toggle');
When I use the same code inside the knockout buttonClick
function, the menu will toggle as intended but it will toggle one more time and stay hidden.
In the jsfiddle I've hooked up on the bootstrap shown event with an alert, there you can see that the menu actually toggles.
The question:
How can force the menu to toggle only once? Or should I use a different approach?
Upvotes: 2
Views: 2373
Reputation: 22753
There is an issue with the click event on the button. The fix is to add clickBubble: false
to the data-bind
on your button. I think your event is bubbling up so it is toggling on and off immediately, so you wouldn't see it.
Check out the working sample:
Markup:
<div class="dropdown" id="myDropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Menu</a>
<ul class="dropdown-menu">
<li>Here goes stuff</li>
</ul>
</div>
<button data-bind="click: buttonClick, clickBubble: false">Button</button>
JS:
var viewModel = function () {
var self = this;
self.buttonClick = function(){
$('.dropdown-toggle').dropdown('toggle');
}
}
ko.applyBindings(new viewModel());
Note 4: Preventing the event from bubbling
By default, Knockout will allow the click event to continue to bubble up to any higher level event handlers. For example, if your element and a parent of that element are both handling the click event, then the click handler for both elements will be triggered. If necessary, you can prevent the event from bubbling by including an additional binding that is named clickBubble and passing false to it, as in this example:
Upvotes: 4
Reputation: 950
I've had no issue doing this on Firefox 31. Your code works actually.
What is your configuration ?
Upvotes: -1