Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
779 views
in Technique[技术] by (71.8m points)

knockout.js - Prevent event bubbling when using the checked binding in knockoutjs

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...