Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use event.preventDefault with KnockoutJs click event handlers?

Tags:

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?

like image 966
jaffa Avatar asked Nov 28 '11 14:11

jaffa


People also ask

What can I use instead of event preventDefault?

Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

How do you bind a function in knockout JS?

The function you want to bind to the element's click event. You can reference any JavaScript function - it doesn't have to be a function on your view model. You can reference a function on any object by writing click: someObject. someFunction .

What is $parent in knockout?

$parent : This is the view model object in the parent context, the one immeditely outside the current context. $root : This is the main view model object in the root context, i.e., the topmost parent context. It's usually the object that was passed to ko.


2 Answers

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/

like image 191
RP Niemeyer Avatar answered Sep 22 '22 19:09

RP Niemeyer


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

like image 31
Matt Shepherd Avatar answered Sep 20 '22 19:09

Matt Shepherd