How do you perform dynamic binding with KnockOut JS?

I am trying to create a view that operators something like this:

enter image description here

The user selects the parent, and then all the children are displayed below, where they can edit the information about the children.

What I would like to know is the right way to change the child grid snap on the fly when the user selects a new parent in the parent grid.

My view model in ko js form looks something like this:

function ViewModel(viewModelFromServer) { var self = this; self.parents = ko.observableArray(convertToKOParents(viewModelFromServer.Parents)); self.activeChildren = ko.observableArray([]); self.changeParent(newParent){ self.activeChildren = newParent.children; } } function Parent(serverParent) { var self = this; self.name = ko.observable(serverParent.Name); self.children = ko.observableArray(convertToKOChildren(serverParent.Children); self.childCount = ko.computed(function() { return self.children.length; }); } function Child(serverChild) { var self = this; self.name = ko.observable(serverChild.Name); self.Age = ko.observable(serverChild.Age); self.Height = ko.observable(serverChild.Height); } 

Now, when the user clicks on the parent line, I want to switch activeChildren to the new parent element, but the binding will not be applied automatically.

Is this the right approach to this kind of model? Should I do it differently, and if so, what would this view model look like, and how do I get the child mesh to snap correctly when the parent element changes?

+6
source share
2 answers

Instead of having activeChildren, you can have activeParent and bind children to it:

 <div data-bind="with: activeParent"> <table> <tbody data-bind="foreach: children"> </tbody> </table> </div> 

And since activeParent will be observable, you just call it and you don't need the changeParent function:

 self.activeParent = ko.observable(); 

In order to change:

 viewModelVariable.activeParent(newParent); 

Also, I think your childCount calculation should access the underlying array by calling children() :

 self.childCount = ko.computed(function() { return self.children().length; }); 
+1
source

I would make the current children a computed value that returns the children property for the selected parent. Something like that:

 function ViewModel(viewModelFromServer) { var self = this; self.parents = ko.observableArray(convertToKOParents(viewModelFromServer.Parents)); self.activeChildren = ko.computed(function() { return self.activeParent.children }); self.activeParent = ko.observable() self.changeParent(newParent){ self.activeParent(newParent) } } 

If you configured jsfiddle without an environment function like convertToKOParents, I can demonstrate it a bit more clearly.

0
source

Source: https://habr.com/ru/post/919058/


All Articles