Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js: child a tags not working when parent li element has click binding

I have a menu that each item toggles it's own submenu, here is the sample code. as you can see submenu item is a tag that links out to google.co.nz

  <ul id="menuHolder">
    <li data-bind="click: showMenu.bind($data, 1)"> 
         Main menu item
        <ul class="submenu" data-bind="visible: selected() == '1'">
            <li>
               <a class="sub-item" href="http://google.co.nz">
                    Submenu item
               </a>
             </li>
        </ul>
    </li>
 </ul>
<script type="text/javascript">
  var menuModel = function () {
    var self = this;
    self.selected = ko.observable(0);        
    self.showMenu = function (data) {
        var s = self.selected();
        if (s > 0 && data == s)
            self.selected(0);
        else
            self.selected(data);
    };     
}
ko.applyBindings(new menuModel(), document.getElementById("menuHolder"));
</script>

everything works only the a tag no longer works, what's wrong here?

like image 617
walter Avatar asked Mar 13 '13 08:03

walter


1 Answers

Your problem is the following: clicking on the link raises the click event which boubles up and gets handled by your showMenu function and by default KO won't trigger the default behavour of the browser so your link won't open.

What you need is to add a click event handler on your link which returns true this tells KO to trigger the browser default behaviour and you may also need to set clickBubble property to false to prevent your showMenu execution:

<a class="sub-item" href="http://google.co.nz"
   data-bind="click: function(){ return true }, clickBubble: false" >
      Submenu item
</a>

Can can read more about the click binding in the documentation.

Demo JSFiddle.

like image 63
nemesv Avatar answered Oct 01 '22 12:10

nemesv