Lazy load drop down options.

by Kishore Polsani

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.1.0.js"></script>
<p>How can I make the the below select the correct option when the options arrive? Expected 'option2' to be selected.</p>
<select data-bind="options: $data.choice.options, optionsText: 'text', optionsValue: 'value', value: $data.choice"></select>

JavaScript

var optionsProvider = (function () {
    "use strict";
    var self = {};
    //container for options data, a sort of dictionary of option arrays.
    self.options = {};
    
    self.init = function (optionData) {
        //pre-populate any provided options data here...
    };
    
    self.get = function(name, initialValue) {
        if (!self.options[name]) {
            self.options[name] = ko.observableArray([{ value: initialValue }]);
             
            //ajax request for options
            //populate self.options[name] with options upon return
            //dummy this with below for example.
            setTimeout(function() { 
                self.options[name]([
                    { text : "option1", value : 1 },
                    { text : "option2", value : 2 },
                    { text : "option3", value : 3 },
                ]); 
            }, 1000); //simulate some delay
        }
        //return reference to observable immediately.
        return self.options[name];
    };
    
    return self;
})();


var simpleModel = function() {
  var initialValue = 2;
  this.choice = ko.observable(initialValue); //hard code selected option to simulated pre-saved selection.
  this.choice.options = optionsProvider.get("SomeOptionType", initialValue);  
};

ko.applyBindings(new simpleModel());