title: Knockout js: Lazy load options for select
body: <p>I am trying to create a lazy loading select with knockout js. Loading the data on demand and getting it to update the UI is simple thanks to knockout. However I have an issue with setting the correct item once the data has been loaded.</p>
  
  <p>Example jsFiddle <a href="http://jsfiddle.net/steeeeeeeeeee/5YFry/" rel="nofollow">here</a></p>
  
  <p>After a bit of digging it appears that knockout overrides the value because it wants to match the model to the options. See 'ensureDropdownSelectionIsConsistentWithModelValue' in knockout-2.2.1.debug.js.</p>
  
  <p>This is a problem for me because at the point it does this, there are no options so it overrides my model value with 0.</p>
  
  <p>I'm fairly new to knockout so I suspect I am approaching this wrong... Has anyone achieved this? or have a better approach to suggest?</p>
  
  <p>I have read Ryan's blog post <a href="http://www.knockmeout.net/2011/06/lazy-loading-observable-in-knockoutjs.html" rel="nofollow">Lazy Loading an Observable in KnockoutJS</a> but I cannot see a way to leverage his approach that would solve my issue.</p>
  
  <p>Thanks in advance for any help :)</p>
  
  <p>Ste.</p>
  
  <p>Code Sample:</p>
  
  <p>Html:</p>
  
  <pre><code>&lt;select data-bind="options: $data.choice.options, optionsText: 'text', optionsValue: 'value', value: $data.choice"&gt;&lt;/select&gt;
  </code></pre>
  
  <p>JS:</p>
  
  <pre><code>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) {
      if (!self.options[name]) {
          self.options[name] = ko.observable([]);
  
          //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() {
      this.choice = ko.observable(2); //hard code selected option to simulated pre-saved selection.
      this.choice.options = optionsProvider.get("SomeOptionType");  
  };
  
  ko.applyBindings(new simpleModel());
  </code></pre>