title: Knockout.js: Using nested observables with mapping plugin
body: <p>I am building a sidebar to filter a main view, like for instance the one at <a href="http://www.johnlewis.com/Men/Men%27s+Jackets+and+Coats/Men%27s+Jackets+and+Coats/Men%27s+Jackets+and+Coats/1216/ProductCategory.aspx" rel="nofollow">John Lewis</a>. I have the code working but it ain't pretty.</p>
  
  <p>I know there are several SO questions on similar lines but I can't quite fathom my own use case.</p>
  
  <p>I need to get the names of the checkboxes from the server ( eg via JSON ) to dynamically create observableArrays on my ShopView.</p>
  
  <p>Here's how it is:</p>
  
  <pre><code>var data = {
      'gender' : [ ],
      'color' : [ ]
  };
  
  var filterMapping = {
      create: function( obj ) {
          return ko.observableArray( obj.data );
      }
  }
  
  var ShopView = new function() {
  
      var self = this;
  
      ko.mapping.fromJS( { filters: data }, filterMapping, self );
  
      // this is the bit I don't like
      this.filterChange = ko.computed(function () {
          for( var key in self.filters )  {
              var obj = self.filters[key]; 
               if( ko.isObservable(obj)){
                  obj();                 
               }             
          }
      });
  
      this.filterChange.subscribe( function( ) {
          //make AJAX request for products using filter state
      });
  
  }
  </code></pre>
  
  <p>My HTML looks as you'd expect:</p>
  
  <h3>Gender</h3>
  
  <pre><code>    &lt;ul&gt;
          &lt;li&gt;&lt;input type="checkbox" value="male" data-bind="checked: filters.gender" /&gt;Male&lt;/li&gt;
          &lt;li&gt;&lt;input type="checkbox" value="female" data-bind="checked: filters.gender" /&gt;Female&lt;/li&gt;
      &lt;/ul&gt;
  </code></pre>
  
  <p>As I say, it works, but it's not nice. In an ideal world I could subscribe to this.filters, eg</p>
  
  <pre><code>this.filters.subscribe( function() { 
      //make AJAX request for products using filter state
  });
  </code></pre>
  
  <p><strong>NB</strong> I'm not trying to do the filtering on the client side - just update my viewmodel when the dynamically-bound checkboxes change.</p>
  
  <p>Any ideas? thanks!</p>