Search code examples
knockout.jsko.observablearray

Update the template on the change of a select from within the parsed template


I have an Observable Array, where using the mapping plugin i map on it a json from server. The json structure is like this:

Data: [{
  NumberOfRooms: 5,
  Category: 1 
  },
  {
  TruckDoorsNo: 5,
  Category: 2
  }]

This json contains data about different type of objects and from the category value we determine what to show and what not to show in my template using:

<div data-bind="foreach: Buildings"> 
<!-- ko if: Category === 1 -->
  <input type="text" data-bind="value: NumberOfRooms" />
  <select data-bind="value: Category">
      <option value="1">Category1</option>
      <option value="2">Category2</option>
  </select>
<!-- /ko -->
<!-- ko if: Category === 2 -->
  <input type="text" data-bind="value: TruckDoorsNo" />
  <select data-bind="value: Category">
      <option value="1">Category1</option>
      <option value="2">Category2</option>
  </select>
<!-- /ko -->
</div>

The problem is that each item's category can be changed from within the parsed template and we want to update the template when this change is happening.

I do not have a knockout Model for this ViewModel and i am mapping the json directly from the server.

How to achieve this? I tried to make the category property observable but this is doing nothing.

I have to add that i just started using Knockout and i am not aware of it's full power.


Solution

  • I found the answer my template was wrong in the first place:

    instead of:

    <!-- ko if: Category === 2 -->
    <!-- /ko -->
    

    the correct way is:

    <!-- ko if: Category() == 2 -->
    <!-- /ko -->
    

    I made the Category property observable like this:

    ko.utils.arrayForEach(viewModelBuilding.Buildings(), function(item)
        {
            item.Category = ko.observable(item.Category);
        });