I have started to play around with knockoutjs and do some simple binding/dependant binding.
My goal is to have 1 <select>
list populated based on the value of another <select>
list. Both are being loaded from an ajax call to my asp.net webservice.
So I have two <select>
lists
<select id="make" data-bind="options: availableMakes, value: selectedMake, optionsText: 'text', optionsCaption: 'Choose a make'"></select>
<select id="model" data-bind="options: availableModels, value: selectedModel, optionsText: 'text', optionsCaption: 'Choose a model'"></select>
Then my javascript looks like this:
$(function () {
// creating the model
var option = function (text, value) {
this.text = text;
this.value = value;
}
// creating the view model
var searchModel = {
availableMakes: ko.observableArray([]),
availableModels: ko.observableArray([]),
selectedMake: ko.observable(),
selectedModel: ko.observable()
}
// adding in a dependentObservable to update the Models based on the selected Make
searchModel.UpdateModels = ko.dependentObservable(function () {
var theMake = searchModel.selectedMake() ? searchModel.selectedMake().text : '';
if (theMake != '') {
$.ajax({
url: "/data/service/auction.asmx/GetModels",
type: 'GET',
contentType: "application/json; charset=utf-8",
data: '{make:"' + theMake + '"}',
success: function (data) {
var makes = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
var mappedModels = $.map(makes, function (item) {
return new option(item.text, item.value);
});
searchModel.availableModels(mappedModels);
},
dataType: "json"
});
}
else {
searchModel.availableModels([]);
}
return null;
}, searchModel);
// binding the view model
ko.applyBindings(searchModel);
// loading in all the makes
$.ajax({
url: "/data/service/auction.asmx/GetMakes",
type: 'GET',
contentType: "application/json; charset=utf-8",
data: '',
success: function (data) {
var makes = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
var mappedMakes = $.map(makes, function (item) {
return new option(item.text, item.value);
});
searchModel.availableMakes(mappedMakes);
},
dataType: "json"
});
});
Currently this works as expected, but I think that I am doing this wrong as the code looks pretty long, and I could do this without using knockoutjs in less code.
Also the way that I am loading up the availableModels
is obviously not correct because I am using a dependentObsevable called UpdateModels
which I added in order to load up the availableModels
based on the value of selectedMake().text
I hope this makes sense and you can point out an improved version of this? Or tell me simply How do I reload the Models based on the Make selection?
Many Thanks,