javascript - Knockout js foreach binding with expand/collapse -
i've read couple tutorials , tried couple hours trying work. goal have multiple links expand/collapse when clicked on. far have 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 have expanded state on parent why expands/collapses. how each item keep track of own expand/collage state?
well creating single dependency
observable's referring parent
issue here .
so need have independent dependency each list item , make use of
$data
refers current context . trick here creating instance each listitem
view:
<ul data-bind="foreach: items"> <a href="#" data-bind="click: toggle, text:linklabel"></a> <button data-bind="text:name"></button> <div data-bind="visible:expanded"> <input data-bind="value:name"></input> </div> </ul>
viewmodel:
function sample(item) { var self = this; self.name = ko.observable(item.name); self.id = ko.observable(item.id); self.expanded = ko.observable(false); self.toggle = function (item) { self.expanded(!self.expanded()); }; self.linklabel = ko.computed(function () { return self.expanded() ? "collapse" : "expand"; }, self); } var viewmodel = function () { var self = this; var json = [{ "name": "bruce", "id": 1 }, { "name": "greg", "id": 2 }] var data = ko.utils.arraymap(json, function (item) { return new sample(item); // making things independent here }); self.items = ko.observablearray(data); }; ko.applybindings(new viewmodel());
working sample here
Comments
Post a Comment