Knockout.js Make every nested object an Observable

后端 未结 6 1745
轻奢々
轻奢々 2020-12-04 22:00

I am using Knockout.js as a MVVM library to bind my data to some pages. I\'m currently building a library to make REST calls to a web service. My RESTful web service returns

6条回答
  •  囚心锁ツ
    2020-12-04 22:09

    By using Knockout-Plugin we can make child elements observable .We have lot of options to manage how we want our data to make observable.

    Here is a sample code :

    var data = {
        people: [
            {
                id: 1,
                age: 25,
                child : [
                    {id : 1,childname : "Alice"},
                    {id : 2,childname : "Wonderland"}
                ]
            }, 
            {id: 2, age: 35}
        ],
        Address:[
            {
                AddressID : 1,
                City : "NewYork",
                cities : [
                    {
                        cityId : 1,
                        cityName : "NewYork"
                    },
                    {
                        cityId :2,
                        cityName : "California"
                    }
                ]
            },
            {
                AddressID : 2,
                City : "California",
                cities : [
                    {
                        cityId :1,
                        cityName : "NewYork"
                    },
                    {
                        cityId :2,
                        cityName : "California"
                    }
                ]
            }
        ],
        isSelected : true,
        dataID : 6
    };
    var mappingOptions = {
        people: {
            create: function(options) {
                console.log(options);
                return ko.mapping.fromJS(options.data, childmappingOptions);
            }
        },
        Address: {
            create: function(options) {
                console.log(options);
                return ko.mapping.fromJS(options.data, childmappingOptions);
            }
        }
    };
    var childmappingOptions = {
        child: {
            create: function(options) {
                return ko.mapping.fromJS(options.data, { observe: ["id","childname"]});
            }
        },
        cities :{
            create: function(options) {
                return ko.mapping.fromJS(options.data, { observe: ["cityId","cityName"]});
            }
        }
    };
    var r = ko.mapping.fromJS(data, mappingOptions);
    

    I have attached a working fiddle: http://jsfiddle.net/wmqTx/5/

提交回复
热议问题