Skip to content

Instantly share code, notes, and snippets.

@johnhunter
Created September 16, 2012 16:01
Show Gist options
  • Save johnhunter/3732969 to your computer and use it in GitHub Desktop.
Save johnhunter/3732969 to your computer and use it in GitHub Desktop.
Example Knockout parameterized template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ko: parameterized template</title>
<style type="text/css">
li.inline {
display: inline-block;
margin: 0 .5em;
}
</style>
</head>
<body>
<script src="lib/jquery-1.7.2.js"></script>
<script src="lib/jquery.tmpl.js"></script>
<script src="lib/knockout-2.1.0.js"></script>
<div data-bind="template: {
name: 'items',
data: colors,
templateOptions: {
title: 'List of colors',
liClass: 'inline'
}
}"></div>
<script type="text/html" id="items">
<h3>${$item.title}</h3>
<ul>
{{each $data}}
<li class="${$item.liClass}" data-bind="template: {
name: 'button',
data: $data[$index]
}"></li>
{{/each}}
</ul>
</script>
<script type="text/html" id="button">
<button data-bind="
click: toggleState,
text: name + ' ' + isActive(),
style: { color: isActive ? 'red' : 'black' }"></button>
</script>
<script>
var vm = {
colors: ko.observableArray([
new Color('red'),
new Color('green'),
new Color('blue'),
new Color('yellow'),
new Color('cyan'),
new Color('magenta')
])
};
console.log(vm.colors()[0])
function Color (name, state) {
this.name = name;
this.isActive = ko.observable(!!state);
return this;
}
Color.prototype.toggleState = function () {
this.isActive = !this.isActive;
console.log(this.name, this.isActive)
};
ko.applyBindings(vm);
</script>​
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment