I found an interesting example on the KnockoutJS site () and I want to implement something similar.
My goal is to check if certain values are available on the client side when a category is selected. If they are not, then I need to fetch them from the server. Unlike the example provided, where the products are already on the client side, in my case I need to first check on the client and only go to the server if the data does not exist.
Can anyone provide me with an example or offer any tips on how to achieve this?
Thank you in advance!
Here is the code snippet I have tried (JavaScript):
function getJsonObject(value) {
return $.parseJSON(value.replace(/"/ig, '"'));
}
var sg = getJsonObject('@ViewBag.SchoolGroups');
var temp = {
schoolGroups: sg,
schoolsBySchoolGroup: undefined,
getSchools: function (schoolGroupId) {
alert(schoolGroupId);
if (this.schoolsBySchoolGroup === undefined) {
//get data from server
}
else {
//verify if data exists
//if not, retrieve from server
}
return "something...";
}
};
$(document).ready(function () {
var CartLine = function () {
var self = this;
self.schoolGroup = ko.observable(sg[0].Id);
self.school = ko.observable();
// Whenever the category changes, reset the product selection
self.schoolGroup.subscribe(function () {
self.school(undefined);
});
};
var Cart = function () {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray([new CartLine()]); // Put one line in by default
// Operations
self.addLine = function () { self.lines.push(new CartLine()); };
self.removeLine = function (line) { self.lines.remove(line) };
};
ko.applyBindings(new Cart());
});
HTML code:
<table>
<thead>
<tr>
<th>Start Date</th>
<th>School Group</th>
<th>School</th>
<th></th>
</tr>
</thead>
<tbody data-bind='foreach: lines'>
<tr>
<td>
<input class='required datepicker' />
</td>
<td>
<select data-bind='options: temp.schoolGroups, optionsText: "Name", optionsValue: "Id", value: schoolGroup'></select>
</td>
<td data-bind="with: schoolGroup">
<select data-bind='options: temp.getSchools($parent.schoolGroup.Id), optionsText: "Name", optionsValue: "Id", optionsCaption: "Select...", value: $parent.school'></select>
</td>
<td>
<a href='#' class="none" data-bind='click: $parent.removeLine'><i class="icon-remove"></i></a>
</td>
</tr>
</tbody>
</table>
<a href='#' class="none" data-bind='click: $root.addLine'><i class="icon-plus"></i></a>
I attempted using $parent and $data without success...