在knockoutjs中使用checked binding时防止事件冒泡 [英] Prevent event bubbling when using the checked binding in knockoutjs

查看:31
本文介绍了在knockoutjs中使用checked binding时防止事件冒泡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 KnockoutJs 和 Twitter Bootstrap 构建用户界面.

我在一个名为 dropdown-toggle 的 Bootstrap 对话框中使用了 checked 绑定.

<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">刻面<span class="caret"></span></a><ul class="下拉菜单"><!-- ko foreach: facets --><li><input type="checkbox" data-bind="checked: Visible"/><span data-bind="text: Name"></span><!--/ko -->

一切都很好,只是我希望在选中复选框时下拉对话框保持打开状态.

这是一个带有示例的小提琴:http://jsfiddle.net/MikeEast/L3KfG/2/

我尝试创建自己的绑定处理程序,它显式地使用检查绑定与 event.preventDefault()event.stopPropagation() 一起打开对话,但防止复选框被选中.

有什么指点吗?

解决方案

听起来您走对了路.你基本上想做相当于:

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

OR 这可以在自定义绑定中完成,例如:

ko.bindingHandlers.stopBubble = {初始化:函数(元素){ko.utils.registerEventHandler(元素,点击",函数(事件){event.cancelBubble = true;如果(事件.停止传播){event.stopPropagation();}});}};

KO 附加的普通点击/事件处理程序将阻止默认操作,除非您返回 true.但是,如果我们挂钩自己的事件处理程序,那么我们只需要防止它冒泡即可.

示例:http://jsfiddle.net/MikeEast/PyNfg/1/

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?

解决方案

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/

这篇关于在knockoutjs中使用checked binding时防止事件冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆