Note that there are some explanatory texts on larger screens.

plurals
  1. POMap JSON data to Knockout observableArray with specific view model type
    primarykey
    data
    text
    <p>Is there a way to map a JSON data object to an observable array and then in turn have each item of the observable array be initialized into a specific type of view model?</p> <p>I've looked at all of knockout's documentation along with the knockout and mapping examples here and I can't find any answer that works for what I'm after.</p> <p>So, I have the following JSON data:</p> <pre><code> var data = { state : { name : 'SD', cities : [{ name : 'Sioux Falls', streets : [{ number : 1 }, { number : 3 }] }, { name : 'Rapid City', streets : [{ number : 2 }, { number : 4 }] }] } }; </code></pre> <p>And I have the following view models:</p> <pre><code>var StateViewModel = function(){ this.name = ko.observable(); this.cities = ko.observableArray([new CityViewModel()]); } var CityViewModel = function(){ this.name = ko.observable(); this.streets = ko.observableArray([new StreetViewModel()]); } var StreetViewModel = function(){ this.number = ko.observable(); } </code></pre> <p>Is it possible, with the given data structure and using knockout's mapping plugin, to have the resulting StateViewModel contain an observableArray populated with 2 CityViewModels, and each CityViewModel containing an observableArray populated with 2 StreetViewModels?</p> <p>Currently using the mapping plugin I'm able to get it to map to a StateViewModel, but the 'cities' and 'streets' collections are populated with generic objects instead of instances of my City and Street view models.</p> <p>They end up with the correct observable properties and values on them, they're just not instances of my view models, which is what I'm after.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload