Question

I am trying to initialize an observable array from a json object which is rendered from the server as Javascript/Json;

Basically I have a simple model (from the server) that looks like this

    var BaseModel = { "changeRequestLocations": 
             [{ "location": "New Zealand", "devices": 
                      [
                        { "id": "5", "deviceName": "Server 1" },  
                        { "id": "6", "deviceName": "Server 2" }
                      ],
              "id": 1 }] };

I then initialize an observable array from the baseModel

    this.changeRequestLocations = ko.observableArray(BaseModel.changeRequestLocations);

This basically does what I want but the "devices" element is an array not an observable array.

I really need to have it as an observable array - is there a way to tell Knockout to do this automatically or do I need to do it manually?

See a fiddle here that shows the case

Was it helpful?

Solution

In itself Knockout does not do this for you automatically, so

  • you do it manually like your jsfiddle
  • you use the Knockout.Mapping plugin which is designed for this scenario: convert plain JavaScript objects to objects with observable properties.

So in your example you just need to write:

this.changeRequestLocations = ko.mapping.fromJS(BaseModel.changeRequestLocations);

and the mapping plugin will convert your location array into an observable array.

Demo JSFiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top