Question

I'm trying to build an complexe view with knockout.js and have a few problems.. The content data for the view model is loaded over ajax as JSON. The JSON is quite complex and has multiple nested objects from which some should be observable and others not.

Here is a little example (real one is some levels deeper)

{
        BaseData:{
            Title:'BaseDataTitle',
            DataArray:[{Title:'obs1'}],//this should be observable
            SecondArray:[{Title:'notobs1'}],//this should not be observable
        },
        DataArray:[{Title:'obs1'}]
    }

http://jsfiddle.net/wPs7e/

is there any possibility to do that with knockout?

thanks for your help!

Was it helpful?

Solution

You'll have to do some work with your objects...you could use the mapping plug-in, however you'll still need to create some objects to receive your data and conditionally apply the bindings...

var KOObject = function(rawdata) {
    var self = this;
    self.BaseData = new BaseDataObject(rawdata.BaseData);
    self.DataArray = rawdata.DataArray; 
}

var BaseDataObject = function(baseData) {
    var self = this;
    self.Title = baseData.Title;
    // you could keep chaining the creation of objects with this concept
    self.DataArray = ko.observableArray(baseData.DataArray);
    self.SecondArray = ko.observableArray(baseData.SecondArray);
}

before you apply your bindings, new up this object

ko.applyBindings(new KOObject(rawdata));

The mapping plugin is a great idea for automating both the serialization and deserialization of data with knockout...it's just not always necessary if you have the option of initializing your data sets manually...it's good practice anyways.

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