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()); 

jsfiddle here

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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -