Reputation: 27350
So for example the observable array is set-up using the mapping function (ko.mapping.fromJS). How do I data-bind the visibility of a div based on a value inside the observable array?
Upvotes: 1
Views: 2740
Reputation: 11538
It is important to note that when you use ko.observableArray
, it is only observing the array and not the individual objects in the array. So if anything is pushed or popped from the array, then knockout will notice that and update the templates but if there is a change in an individual object of an array e.g. a certain property of an array member is changed, knockout will not update the templates.
The solution is to observe array members inside the array separately which you want to subscribe to. In your case lets say if the value inside the observable array reside in the first index member then you would need to do the following in your view model:
theArray: ko.observableArray(initialArray);
theValue: ko.observable(this.theArray[0]);
and div visibility :
<div data-bind="visible: theValue.something"></div>
EDIT:
The problem with your scenario is that the if a certain users becomes an Admin, knockout will NOT render the template because it is not tracking individual properties of each user in the array. It will ONLY render the template when you add/delete the users array.
To ensure that it re-renders the template if a user is set as Admin, we need to do something like this >
//declare the view model
var viewModel = {
users: ko.observableArray(listOfUsers); //you need to pass the users list array you get from ko.mapping
}
//make each array member observable
for (var i = 0; i < viewModel.users().length; i++) {
viewModel.users()[i] = ko.observable(users()[i]);
}
Upvotes: 1