I need to prepopulate a knockout component when the document is ready.
This is the code I have written:
function Finding(id, trigger) {
var self = this;
self.id = ko.observable(id);
self.trigger = ko.observable(trigger);
}
function FindingViewModel() {
let self = this;
self.findings = ko.observableArray();
self.addFinding = function () {
self.findings.push(new Finding(self.findings().length + 1, ""));
};
self.removeFinding = function (finding) {
self.findings.remove(finding);
ko.utils.arrayForEach(self.findings(), function (value, i) {
self.findings.replace(value, new Finding(i + 1, value.trigger()));
});
};
self.update = function (data) {
var findings = data.findings;
for (var index = 0; index < findings.length; ++index) {
var finding = findings[index];
self.findings.push(new Finding(self.findings().length + 1, finding.trigger));
}
};
}
ko.components.register('finding', {
template: `<table>
<tbody data-bind="foreach: findings">
<tr>
<td><span data-bind="text: id"/></td>
<td><input data-bind="value: trigger"/></td>
<td><a href="#" data-bind="click: $parent.removeFinding">Remove</a></td>
</tr></tbody></table>
<button data-bind="click: addFinding">Add a Finding</button>`,
viewModel: FindingViewModel
});
$(function () {
ko.applyBindings();
$.getJSON("/_get_findings", function (data) {
//findingModel.update(data);
})
});
What is the best way to access the Viewmodel from the finding component in order to update data from within the getJSON function?