How to make object properties in a knockout observable array be observable?
Asked Answered
B

3

6

When 'create' option is used in knockout mapping we would make the array an observable array. But how do we make the properties of each object in the observable array an observable ?

In this example from the knockout documentation, the children array is made an observable array but I want to make all the elements like id, name within each object literal also to be an observable. How do we achieve that. Just put a ko.observable on each newed object in the create block ?

var data = {
    name: 'Graham',
    children: [
        { id : 1, name : 'Lisa' }
    ]
};

// Your custom data model
var myChildModel = function (data) {
    this.id = data.id;
    this.name = data.name;
};

var mapping = {
    'children': {
        create: function(options) {
            return new myChildModel(options.data);
        }
    }
};

var viewModel = ko.mapping.fromJS(data, mapping);
Boardman answered 29/8, 2014 at 16:0 Comment(0)
P
2

Simply:

var viewModel = ko.mapping.fromJS(data);

It does everything, make both properties and arrays observable. The second parameter of this method is only for the purpose of customization. You do not have to use it if you do not need!

Powered answered 9/11, 2017 at 21:9 Comment(0)
C
1

Per the documentation:

  • All properties of an object are converted into an observable.

Thus, down in the section regarding Customizing object construction using “create” it states

Of course, inside the create callback you can do another call to ko.mapping.fromJS if you wish.

The example provided is as follows:

var myChildModel = function(data) {
  ko.mapping.fromJS(data, {}, this);

  this.nameLength = ko.computed(function() {
    return this.name().length;
  }, this);
}

Naturally, this would convert all the properties. More detailed configuration could then be applied specifically to that mapping call to handle custom requirements.

Cicada answered 29/8, 2014 at 16:25 Comment(0)
L
1

The quick answer is make the properties of the object observable

var myChildModel = function (data) {
    this.id = ko.observable(data.id);
    this.name = ko.observable(data.name);
;

It's also probably the easiest way, though there are others

Lareelareena answered 29/8, 2014 at 16:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.