I'm creating a list of checkboxes using a knockout.js foreach loop. I have an observable array that holds the value of the checkboxes, but when I call the function to check their values the this element is referring to the parent element i.e. the viewModel. How can I access the element of the array that relates to the element that is clicked on?
I have tried removing the $parent reference from the following code, but that threw this error: Message: getSampleValue is not defined
This is the foreach loop that creates the checkboxes:
<!-- ko foreach: sampleList -->
<div data-bind="css: { hasValue: $parent.getSampleValue() }">
<span data-bind="click: $parent.sampleClick, text: name"></span>
<div data-bind="click: $parent.sampleClick" class="spot fa fa-square"></div>
</div>
<!-- /ko -->
And these are the functions defined in the ko view model:
sampleViewModel = function (data) {
var self = this;
self.sampleList = ko.observableArray(data.sampleList);
self.sampleClick = function () {
this.isChecked = !this.isChecked;
}
self.getSampleValue = function () {
return this.isChecked;
}
}
And the sampleList is in the format:
{
{
"name": "name1",
"isChecked": false
},
{
"name": "name2",
"isChecked": true
}
}
Expected results: The function getSampleValue should be called when the value of isChecked for a given item in the array is changed and that should update the value on the UI. The isChecked value that is returned from that function should be of the correct element in the array and not the parent element.
Actual results: The function is called, but appears to be only called on creation of the checkboxes and not when the isChecked value is updated, and the this within the function is the parent element of the caller and therefore doesn't have an isChecked value.
Any help with this is much appreciated.
EDIT: So changing this line:
<div data-bind="css: { hasValue: $parent.getSampleValue() }">
To this:
<div data-bind="css: { hasValue: isChecked }">
Seems to display the correct values on loading, but they still don't update on the UI even though the values of the observable array are being changed.