Invoking a custom method when a value changes

Is there a way to call once some method of changing the value? I created a wrapper for bindHandlers.value that call this method:

var update = bindingHandlers.value.update; bindingHandlers.value.update = function(element, valueAccessor, allBindingAccessor, viewModel) { var newValue = ko.utils.unwrapObservable(valueAccessor()); var elementValue = ko.selectExtensions.readValue(element); var valueHasChanged = (newValue != elementValue); update(element, valueAccessor, allBindingAccessor, viewModel); if (valueHasChanged) { myMethod(); } } 

Unfortunately, when I change some value, myMethod is called twice because the dependencyObservable is also changed. Any ideas?

+6
source share
1 answer

If you just want to subscribe to the changed value, you can subscribe to any observable:

 var viewModel = { property: ko.observable() }; viewModel.property.subscribe(function(newValue) { //do stuff }); 

To subscribe to all properties of an object, you can do something like:

 function subscribeAll(viewModel) { for(var propertyName in viewModel) { if(viewModel[propertyName].subscribe === 'function') { viewModel[propertyName].subscribe(function(newValue) { //do stuff } } } } 
+8
source

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


All Articles