Reputation: 6068
Below is my first piece of knockoutjs code i've written. In the code below, i have two list boxes. the first is populated after the page loads and works fine. What i want to do next is that when a user selects an item from the cmbDataSets listbox, i want to make a second ajax call to populate the 'instruments' property of my view model. later when the user selects an instrument, i want to make yet another call to fetch data that i will display in a grid (using slickgrid.js).
Right now, i'd like to understand what are the ways or best practice for accomplish this. i think i can simply add normal html/javascript selection change event handler on the first list box to accomplish this...but i'm not sure if that is the recommended way (i know it's not the MVVM way anyway). I feel that since selectedDataSet is an observable, i should be able to chain that to an event handler as well..no? My question is how? Can i define an onSelectedDataSetChange method on my viewmodel and if so, how do i 'hook' it into the actually selection change of the cmbDataSets control?
<div class="container">
<label for="cmbDataSets">Select list:</label>
<select id="cmbDataSets" data-bind="options: dataSets, optionsText:'descr', value:selectedDataSet, optionsCaption:'Choose' " class="form-control"></select>
<label for="cmbInstruments">Select instrument:</label>
<select id="cmbInstruments" data-bind="options: instruments, optionsText:'intrument', value:selectedInstrument, optionsCaption:'Choose' " class="form-control"></select>
</div>
<script type="text/javascript">
$(document).ready(function () {
var viewModel = {
dataSets: ko.observableArray(),
instruments: ko.observableArray(),
selectedDataSet: ko.observable(),
selectedInstrument: ko.observable()
}
$.ajax({
url: '/ds/sets',
type: "GET",
dataType: "json",
success: function (data) {
debugger;
console.log(data);
viewModel.dataSets(data);
}
});
ko.applyBindings(viewModel);
});
</script>
Upvotes: 0
Views: 386
Reputation: 286
Mike.
Check this code, for setting change event in the View:
<select data-bind="event: { change: selectionChanged }"></select>
and then a proerty in the ViewModel:
selectionChanged: function(event) { }
Is this is what you were searching for? Other than this, I have a small suggestions - SelectedDataSet and selectedInstrument can be also observable arrays. The difference is that you are going to use not the 'value' biding, but the 'selectedOptions' one. This will help you when you have multiple selection, but even when it's a single one, it's a better option, I think.
Upvotes: 1
Reputation: 123
You can subscribe to the first boxes selectedOption observable and make a call whenever it changes.
selectedOption = ko.observable();
selectedOption.subscribe(function (newValue) {
secondBoxSource(ajaxCallFunction(newValue));
});
Where ajaxCallFunction() is the function you use to fetch the data for the second box, and newValue is the newly selected value from the first box.
Upvotes: 1