Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent event bubbling when using the checked binding in knockoutjs

Tags:

I'm building a UI using KnockoutJs and Twitter Bootstrap.

I'm using the checked binding inside a Bootstrap dialogue called dropdown-toggle.

<div class="btn-group">     <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">         Facets         <span class="caret"></span>     </a>     <ul class="dropdown-menu">         <!-- ko foreach: facets -->         <li>             <input type="checkbox" data-bind="checked: Visible" />              <span data-bind="text: Name"></span>         </li>         <!-- /ko -->     </ul> </div> 

Everything is fine except that I would like the drop down dialogue to remain opened when checking the checkboxes.

Here is a fiddle with an example: http://jsfiddle.net/MikeEast/L3KfG/2/

I have tried creating my own binding handler which uses the checked binding explicitly together with event.preventDefault() and event.stopPropagation() which leaves the dialogue opened, but prevents the checkbox to be checked.

Any pointers?

like image 997
Mikael Östberg Avatar asked Jan 14 '13 15:01

Mikael Östberg


People also ask

How do you stop an event from bubbling?

If you want to stop the event bubbling, this can be achieved by the use of the event. stopPropagation() method. If you want to stop the event flow from event target to top element in DOM, event. stopPropagation() method stops the event to travel to the bottom to top.

How can you stop the event bubbling up in JS?

To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.

How do you bind data in KnockoutJS?

Binding syntaxThe binding name should generally match a registered binding (either built-in or custom) or be a parameter for another binding. If the name matches neither of those, Knockout will ignore it (without any error or warning). So if a binding doesn't appear to work, first check that the name is correct.


1 Answers

It sounds like you were on the right track. You basically want to do the equivalent of:

click: function() { return true; }, clickBubble: false 

OR This could be done in a custom binding like:

ko.bindingHandlers.stopBubble = {   init: function(element) {     ko.utils.registerEventHandler(element, "click", function(event) {          event.cancelBubble = true;          if (event.stopPropagation) {             event.stopPropagation();           }     });   } }; 

The normal click/event handler attached by KO will prevent the default action unless you return true. However, if we hook up our own event handler, then we only need to prevent it from bubbling.

Sample: http://jsfiddle.net/MikeEast/PyNfg/1/

like image 165
RP Niemeyer Avatar answered Oct 24 '22 15:10

RP Niemeyer