JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<span>simple example</span></br>
<div data-bind="foreach : comments">
<div><span data-bind="text:id"></span> <span data-bind="text:text"></span></div>
</div>
</br></br>
<span>Somthing like this is what I want</span></br>
<div data-bind="myListView: {items:comments,selectedItem : selectedComment}">
<div><span data-bind="text: id"></span> <span data-bind="text: text"></span></div>
</div>
<br />
<br />
<div data-bind="with: selectedComment">
Selected: <span data-bind="text: text"></span>
</div>
<a href="javascript:;" data-bind="click:addComment">Add Comment</a>
CSS
.selected { color: blue }
JavaScript
ko.bindingHandlers.myListView = {
init: function(element) {
var $element = $(element),
originalContent = $element.html();
$element.data("original-content", originalContent);
return { controlsDescendantBindings: true }
},
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
//get the list of items
items = value.items(),
//get a reference to the selected item observable
selectedItem = value.selectedItem,
//get a jQuery reference to the element
$element = $(element),
//get the currently selected item
currentSelected = selectedItem(),
//get the current content of the element
elementContent = $element.data("original-content");
$element.html("");
for (var index = 0; index < items.length; index++) {
(function() {
//get the list of items
var item = ko.utils.unwrapObservable(items[index]),
//create a child element with a click handler
$childElement = $(elementContent)
.click(function() {
//remove selected class on all siblings
$(this).siblings().removeClass("selected");
//add selected class on this item
$(this).addClass("selected");
//set the observable 'selected item' property on the source view model
selectedItem(item);
});
ko.applyBindings(item, $childElement[0]);
//add the selected class if this item is the current selected item
if (item == currentSelected) {
$childElement.addClass("selected");
}
...