How do I use event.preventDefault with KnockoutJs

2019-04-03 05:28发布

I have the following table row as a script template in KnockoutJs:

    <script id="inboxTemplate" type="text/html">           
    <tr data-bind="click: function() { viewInboxModel.selectAction($data); }">                                 
        <td>...</td>                 
        <td>${ CreateDate }</td>               
        <td data-bind="click: function(e){ e.preventDefault();viewInboxModel.clearAction($data); }"><img src="/Content/images/delete.png" height="16px" width="16px"> </td>
    </tr>            
    </script>

The problem is when I click the delete button, it is also running the selectAction() method. I've tried using e.preventDefault() in both selectAction click handler and the clearAction() clicker handler to no avail. Is there anyway KnockoutJs can prevent the underlying row from now being clicked if the delete button is clicked?

2条回答
孤傲高冷的网名
2楼-- · 2019-04-03 06:07

If you have jQuery referenced, then you can safely call e.stopImmediatePropagation(); in your handler, as it is passed the jQuery event object. If you are not using jQuery, then you could still do something like:

e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();

http://jsfiddle.net/rniemeyer/mCxjz/

查看更多
来,给爷笑一个
3楼-- · 2019-04-03 06:18

As per @Benoit Drapeau's comment:

In more recent versions of Knockout you use clickBubble: false. e.g.

<td data-bind="click: myFunction, clickBubble: false"> </td>

http://knockoutjs.com/documentation/click-binding.html

查看更多
登录 后发表回答