Is it possible to pass to Knockout the default value of a select element when binding the options through AJAX?

http://stackoverflow.com/questions/9570173/is-it-possible-to-pass-to-knockout-the-default-value-of-a-select-element-when-bi

by Keyur Patel

HTML

<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<script src="https://rawgithub.com/SteveSanderson/knockout.mapping/master/build/output/knockout.mapping-latest.debug.js"></script>
<p><select data-bind="options: values, value: value"></select></p>

JavaScript

var viewModel = function () {
    var self = this;

    // The underlying observable where
    // the selected value is stored.
    self.value = ko.observable();

    // The observable bound to
    // the value of the drop down.
    self.values = ko.mapping.fromJS([]);

    // Simulate the AJAX request which fetches the actual value,
    // this request must complete before the second one.
    setTimeout(function () {
        self.initialValue = "b";
        self.value("b");
    }, 1000 * 1);

    // Simulate the AJAX request which fetches the available values,
    // this reqest must complete after the first one.
    setTimeout(function () {
        ko.mapping.fromJS(["a", "b", "c", "d"], {}, self.values);
        if (self.initialValue) {
             self.value(self.initialValue);
             self.initialValue = null;
        }    
    }, 1000 * 2);
};

$(document).ready(function () {
    ko.applyBindings(new viewModel());
});