JSFiddle - React, Tailwind, and code Playground

by stevegreatrex

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>
<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 = {
    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();

        //clear the parent of any existing children
        $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 = $("<li>")
                    .text(item.id() + " " + item.text())
                    .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);
                    });

                //add the selected class if this item is the current selected item
                if (item == currentSelected) {
                    $childElement.addClass("selected");
                }
                
                //add the child to the parent
                $element.append($childElement);
            })();
        }

    }
};

var Comment = function(id, text) {
    this.text = ko.observable(text);
    this.id = ko.observable(id);
};

var ViewModel = function(first, last) {
    this.comments = ko.observableArray([new Comment(1, "Comment1"),...