Display knockout data from the server, lost subscriptions

I am trying to present several selections with selected values ​​from the JSON backend to the knockout representation model. And it was necessary to restore this JSON when each choice was changed, the first time everything was fine, but if I applied the mapping again (ko.mapping.fromJS (test_data, ViewModel)), all subscriptions are lost, does anyone know how to avoid this situation?

jsfiddle (I don’t know why selects does not have its own values, without jsfiddle everything is fine): http://jsfiddle.net/0bww2apv/2/

$(ViewModel.attributes()).each(function(index, attribute) { attribute.attribute_value.subscribe(function(name) { console.log('SUBSCRIBE', name); var send_data = {}; $(ViewModel.attributes()).each(function (index, attribute) { send_data[attribute.attribute_name.peek()] = attribute.attribute_value.peek(); if (attribute.attribute_value() === null) { send_data = null; return false; } }); if (send_data) { console.log('REQUEST TO BACKEND: ', ko.toJSON(send_data)); ko.mapping.fromJS(test_data, ViewModel); // subscriptions is lost here ! } }); }); 
0
source share
1 answer

Finally, I solved my own question using the knockout.reactor plugin . If we remove all the auxiliary constructs, it will look like this:

 var ViewModel = ko.mapping.fromJS(test_data); ko.applyBindings(ViewModel); ko.watch(ViewModel, { depth: -1 }, function(parents, child, item) { // here we need to filter watches and update only when needed, see jsfiddle ko.mapping.fromJS(test_data2, {}, ViewModel); }); 

Thus, we update the selection and have no problems with subscription recursions.

full version (see the end of the console for details): http://jsfiddle.net/r7Lo7502/

0
source

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


All Articles