How can one observe the properties of an object in an observable knockout array?

When the Create option is used in the knockout view, we will make the array an observable array. But how can we make the properties of each object in an observable array observable?

In this example, from the knockout documentation, the children array is created by the observable array, but I want all the elements, such as id, name in each object literal, to also be visible. How do we achieve this? Just put ko.observable on every new 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); 
+5
source share
3 answers

In the documentation :

  • All object properties are converted to observables.

Thus, in the section on setting up building an object using "create" ,

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

The above example is as follows:

 var myChildModel = function(data) { ko.mapping.fromJS(data, {}, this); this.nameLength = ko.computed(function() { return this.name().length; }, this); } 

Naturally, this transforms all properties. A more detailed configuration can then be applied specifically to this display call to handle user requirements.

+1
source

The quick answer is to make object properties observable

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

This is also probably the easiest way, although there are others

+1
source

Simply:

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

It does everything that allows you to observe both properties and arrays. The second parameter of this method is for configuration purposes only. You do not need to use it if you do not need it!

0
source

Source: https://habr.com/ru/post/1201429/


All Articles