Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bootstrap button dropdowns with knockout

I'm attempting to use bootstrap's nicely styled button dropdowns with knockout. Unfortunately the dropdowns are built using links rather than <select> and knockout-bootstrap doesn't have any handlers that help.

I've been able to get all the stylings to work (button type, icons, selected/deselected). But, I still can't get the click function to work:

JS Fiddle Example

<div class="btn-group">
<!-- Change button type based on status -->
<button type="button" class="btn btn-small dropdown-toggle" data-bind="css: {'btn-default' : status().statusName=='Matched', 'btn-danger' : status().statusName=='None', 'btn-info' : status().statusName=='Set'}" data-toggle="dropdown">

  <!-- Add Glyph based on status -->
  <span class="glyphicon" data-bind="css: {'glyphicon-ok' : status().statusName=='Matched', 'glyphicon-remove' : status().statusName=='None', 'glyphicon-list' : status().statusName=='Set'}"></span> <span data-bind="text: status().statusName"> </span> <span class="caret"></span>
</button>

<!-- Loop for status -->
<ul class="dropdown-menu" role="menu" data-bind="foreach: $root.availableStatus">
  <!-- Disable item if selected -->
  <li data-bind="css: {'disabled' : statusName==$parent.status().statusName}">
    <!-- Not working -->
    <a href="#" data-bind="click: $root.updateStatus"><span class="glyphicon" data-bind="css: {'glyphicon-ok' : statusName=='Matched', 'glyphicon-remove' : statusName=='None', 'glyphicon-list' : statusName=='Set'}"></span> <span data-bind="text: statusName"></span></a>]
like image 491
Stephen Edmondson Avatar asked Sep 04 '13 20:09

Stephen Edmondson


1 Answers

Modified JS Fiddle Example

Steps to reproduce

  1. Get rid of updateStatus function on your $root. You don't need it for this simple task.

  2. Bind the click event to $parent.status.

    We want the status function (a ko.observable) on the current Article to be called. At the point where the anchor is defined, the context parent is the Article, so you want to use $parent.status. The current context, which is the element of $root.availableStatus being clicked, is the argument that will be passed to the status function.

     <a href="#" data-bind="click: $parent.status">...</a>
    
like image 138
Timothy Shields Avatar answered Oct 09 '22 02:10

Timothy Shields