[My first attempt at describing the issue was clear as mud; I significantly reworked it in the name of clarity. I hope I haven’t failed miserably…again.]
I’m attempting to set up a master/details view using knockout where the details pane includes a list of checkboxes. I have an array of User objects, each of which has in turn an array of UserPermission objects where the PermissionId property is what should determine if the checkbox is checked.
So, in short: There’s a master list of users, from which you select one to view details. In the details pane, I have a list of checkboxes (generated from a list of available permissions). Whether or not a given checkbox is checked should be determined by the persences of a matching PermissionId within the array of UserPermission objects associated with the current user.
My question is – how do I get the checkboxes to use the user.UserPermissions.PermissionId for the checked binding?
Here’s a jsfiddle of my attempt thus far, and here’s another approach I’ve tried.
After a bit of tinkering, I’ve got a solution for you, though it’s not a trivial change.
I made a few attempts at tweaking what you had, but it became obvious that I needed to approach the problem differently.
So, I started by separating the population of the view model from the definition of the view model.
Here’s the view model definition:
This is the same as what you had, except that the function does not expect data to be passed in.
The binding of this view model now looks like this:
Of course, the details of the
addPermissionsandaddUserAccountsfunctions are in my resulting fiddle, and I’ll provide the link to that in a bit.Let me first discuss the solution for binding whether or not a checkbox is checked.
I took a look at the documentation on using checked, and I noticed that in one of the examples, the bound value is an array.
So, to take advantage of that, I created a
UserAccountclass:When a
UserAccountis added to the view model, it uses the following function:Notice the for loop in this function, which is simply adding each of the PermissionId values from the UserPermissions array to the
userPermissionsobservableArray of theUserAccount.Note also that the available permissions are now each represented by an instance of the following
Permissionclass:[The values of those
Permissionproperties aren’t going to change here, so no need to make those observables.]Now, given all that background, here’s how I bound the checkboxes so that the proper checkboxes are checked:
This code appears within the
with: currentUserblock, so$parentiscurrentUserHere’s the link to the fiddle that contains my solution: http://jsfiddle.net/jimmym715/eByAa/
Oh, and I added the following code to the view to confirm that
userPermissionsis getting updated with each check/uncheck of a checkbox.I hope this solution suits your needs. Let me know if you have any questions.