Can't bind nested JSON to knockout

I am trying to pass JSON for knockout and display it and I was able to do it for the first few elements. However, I am having problems with nested objects. What I'm trying to achieve is to show the desc and value fields for each of A1, A2, A3 / B1, B2, B3 ..

I've looked over a million examples and tried different versions, but still can't figure out how the mapping works.

Many thanks for your help.

JS:

function jsonSubsetModel (desc,value){
    var self = this;
    self.desc = ko.observable(desc);
    self.value = ko.observable(value);
    }


    var myModel = function(){
        var jsonUrl = '/myjson.json';
        var self = this;
        var mapped = {};

        //Data
        self.date = ko.observable();
        self.time = ko.observable();

        self.set1 = ko.observableArray([]);
        self.set2 = ko.observableArray([]);



    $.getJSON(jsonUrl,function (data) {     
    self.date(data.Date);
    self.time(data.Time);   
    self.img(data.ImgURL);

    mapped = ko.mapping.fromJS(data);
    self.set1(mapped.SET1);
    self.set2(mapped.SET2);             
    });

    };  

    ko.applyBindings(new myModel());    

      

HTML:

<!-- This works -->
    <span data-bind="text: date"></span><br>
    <span data-bind="text: time"></span><br>
    <span data-bind="text: img"></span><br>

<!-- This doesn't -->    
    <p data-bind = "foreach:{data: set1, as:'subset'}">
    <span data-bind="text: subset.desc"></span>
    <span data-bind="text: subset.value"></span>    
    </p>

      

JSON:

{    
"Date":"21/02/2013",
"Time":"13:55",    
"SET1": {       
            "A1":{          
            "desc":"descA1",
            "value":"30",               
            },
            "A2":{          
            "desc":"descA2",
            "value":"30",
            },
            "A3":{          
            "desc":"descA3",
            "value":"30",
            }                                           
    },

    "SET2": {       
            "B1":{          
            "desc":"descA1",
            "value":"30",
            },
            "B2":{          
            "desc":"descA1",
            "value":"30",
            },
            "B3":{          
            "desc":"descA1",
            "value":"30",
            }                       
    }
}

      

+3


source to share


1 answer


knockout.js

foreach

works with Array

. What you provide is an object. Change your object to:



"SET1": [      
            {          
            "desc":"descA1",
            "value":"30",               
            },
            {          
            "desc":"descA2",
            "value":"30",
            },
            {          
            "desc":"descA3",
            "value":"30",
            }                                           
    ],

      

+3


source







All Articles