Skip to content

Instantly share code, notes, and snippets.

@sgentile
Created May 13, 2011 14:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgentile/970636 to your computer and use it in GitHub Desktop.
Save sgentile/970636 to your computer and use it in GitHub Desktop.
KnockoutJS with History
<!doctype html>
<html lang="en">
<head>
<title>knockout binding test</title>
<style type="text/css">
#sidebar { float: left; width: 15em; }
#details { float: left; }
#sidebar li { list-style: none; }
#sidebar a { list-style: none; background-color: silver; width: 8em; margin-bottom: 0.5em; padding: 0.5em; display:block; }
#sidebar a.selected { background-color: Navy; color: white; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="http://github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js"></script>
<script src="https://github.com/asual/jquery-address/raw/master/src/jquery.address.js"></script>
<script src="http://github.com/SteveSanderson/knockout/raw/master/build/output/knockout-latest.js"></script>
<script type="text/javascript">
// This could be made more sophisticated as an external plugin
function linkObservableToUrl(observable, hashPropertyName) {
// When the observable changes, update the URL
observable.subscribe(function(value) {
$.address.parameter(hashPropertyName, value)
});
// When the URL changes, update the observable
$.address.change(function(evt) {
observable(evt.parameters[hashPropertyName])
});
}
</script>
<script type="text/javascript">
function productDataViewModel() {
this.allProducts = [
{ name: 'Cat', legs: '4', price: 50 },
{ name: 'Parrot', legs: '2', price: 85 },
{ name: 'Monopod', legs: '1', price: 15 },
];
this.selectedProductName = ko.observable();
linkObservableToUrl(this.selectedProductName, "prod");
this.selectedProduct = ko.dependentObservable(function() {
// Fetch the actual product object based on selectedProductName
return ko.utils.arrayFirst(this.allProducts, function(p) {
return p.name == this.selectedProductName()
}, this);
}, this);
}
var viewModel = new productDataViewModel();
$(function() { ko.applyBindings(viewModel); });
</script>
</head>
<body>
<div id="sidebar">
<ul data-bind="template: { name: 'sidebarTemplate', foreach: allProducts }"> </ul>
</div>
<div id="details" data-bind="template: { name:'detailsTemplate', data: selectedProduct() }"> </div>
<script type="text/html" id="sidebarTemplate">
<li><a href="#" data-bind="click: function() { viewModel.selectedProductName(name) },
css: { selected: name == viewModel.selectedProductName() }">${ name }</a></li>
</script>
<script type="text/html" id="detailsTemplate">
<h2>${ name }</h2>
<div>Legs: <input data-bind="value: legs" /></div>
<div>Price: <input data-bind="value: price" /></div>
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment