I’ve tried to use knockout.js (KO) with bootstrap and I found that it will not work out of the box. The main reason – bootstrap will prevent the click events to go to knockoutjs.
I had two challenges:
1. How to notify KO about the click event without breaking bootstrap?
2. How to do KO data binding with the radio buttons?
After some investigation/googling the answer for challenge 1 became apparent – use custom bindings in knockoutjs: http://knockoutjs.com/documentation/custom-bindings.html
That solved the click event on the buttons.
The answer for number 2: How to use knockoutjs to create dynamically the items (buttons) in my bootstrap radio button group? – It was harder for me – All examples were with static/predefined radio buttons.
The solution came again from the KO documentation – I just did a careful modification of their example for the checkbox to a radio button.
I have the working example below in a gist extracted from my jsfiddle
The key code:
<div class="btn-group" data-toggle="buttons" data-bind="foreach: items"> <label class="btn btn-primary"> <input type="radio" name="options" data-bind="checkedValue: $data.id, bsChecked: $root.chosenItem" /> <span data-bind="text: itemName"></span> </label> </div>
..and the full gist:
If you have any questions, feel free to use the comments section bellow.
Happy coding and let’s code the planet togeter! 🙂