Playing with knockout Indexes in nested lists.
by marrok
HTML
<ul id="people" data-bind='template: { name: "personTmpl", foreach: people }'>
</ul>
<script id="personTmpl" type="text/html">
<li>
<a class="remove" href="#" data-bind="click:function(){console.log($index)}"> x </a>
<span data-bind='text: name'></span>
<a class="add" href="#"> add child </a>
<ul data-bind='template: { name: "personTmpl", foreach: children }'></ul>
</li>
</script>
JavaScript
var Person = function(name, children) {
this.name = ko.observable(name);
this.children = ko.observableArray(children || []);
};
var PeopleModel = function() {
this.people = ko.observableArray([
new Person("Bob", [
new Person("Jan"),
new Person("Don", [
new Person("Ted"),
new Person("Ben", [
new Person("Joe", [
new Person("Ali"),
new Person("Ken")
])
]),
new Person("Doug")
])
]),
new Person("Ann", [
new Person("Eve"),
new Person("Hal")
])
]);
this.addChild = function(name, parentArray) {
parentArray.push(new Person(name));
};
};
ko.applyBindings(new PeopleModel());