<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"),...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.