Reputation: 7001
I have a observableArray variable which is having array like below:
self.EmployeeNames = ko.observableArray([]);
self.EmployeeNames.push({id: 1, name: 'Jasmine', isActive: false});
self.EmployeeNames.push({id: 2, name: 'Jhon', isActive: true});
self.EmployeeNames.push({id: 3, name: 'juliet', isActive: false});
And in my application inside HTML, I bind it using Knockout foreach
binding as shown below:
<div data-bind="foreach: EmployeeNames">
<div class="container" data-bind="text: $data.name, css: {active: isActive}, click: $parent.setEmployeeToActive">
</div>
</div>
In above code, as you see when isActive is set to true for any of the employee, a css class is applied.
Now when I click on another employee name, it should set the isActive to true for that employee and css class should be updated accordingly.
In order to achieve this, I have click binding
and whenever user click on the employeeName, I just update the array as shown below:
self.setEmployeeToActive = function(selectedEmp) {
self.EmployeeNames().forEach(function(emp){
if(emp.id === selectedEmp.id) {
emp.isActive = true;
}
else {
emp.isActive = false;
}
});
self.EmployeeNames.valueHasMutated();
};
But it is not reflected in HTML.
I tried with valueHasMutated
but no luck.
Upvotes: 0
Views: 84
Reputation: 547
The members of the array elements must also be observable.
self.EmployeeNames.push({id: ko.observable(1), name: ko.observable('Jasmine'), isActive: ko.observable(false)});
Upvotes: 1