I've read a couple tutorials and tried for a couple hours trying to get this to work. My goal is to have multiple links that expand/collapse when they are clicked on. So far I have the following:
HTML:
<ul data-bind="foreach: items">
<a href="#" data-bind="click: $parent.toggle, text: $parent.linkLabel"></a>
<button data-bind="text: name, click: $parent.clickTask"></button>
<div data-bind="visible: $parent.expanded">
<input data-bind="value: name"></input>
</div>
</ul>
JS:
var viewModel = function() {
var self = this;
self.items = [{"name":"bruce","id":1},{"name":"greg","id":2}]
self.expanded = ko.observable(false);
self.linkLabel = ko.computed(function () {
return self.expanded() ? "collapse" : "expand";
}, self);
self.toggle = function (item) {
self.expanded(!self.expanded());
};
};
ko.applyBindings(new viewModel());
I understand right now I have the expanded state on the parent which is why everything expands/collapses. How would I get each item to keep track of its own expand/collage state?
I was just solving something very similar and I think there is a way to get around without adding any logic to the ViewModels.
The following code works for a table where each row is expandable:
It uses 2 times the attr binding, once to define the id of the generated detail row and once for setting the data-target of the collapse toggle.
Your example could be modified in the following way and you won't need the "expanded" observable at all.
well you are creating a
single dependency
for all observable's by referringparent
which is the issue here .view:
viewModel:
working sample up here