Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke custom method on value changed

Is there a way to invoke one time some method on value changed? I created wrapper for bindingHandlers.value that invoke 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();
    }
}

Unfortunatelly when I change some value myMethod is called two times becuase come dependencyObservable is also changed. Any ideas?

like image 590
Sławomir Rosiek Avatar asked Nov 16 '11 14:11

Sławomir Rosiek


1 Answers

If you just want to subscribe to a value changed, 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 could do something like:

function subscribeAll(viewModel) {
    for(var propertyName in viewModel) {
        if(viewModel[propertyName].subscribe === 'function') {
            viewModel[propertyName].subscribe(function(newValue) {
                //do stuff
            }
        }
    }
}
like image 51
Paul Tyng Avatar answered Sep 30 '22 13:09

Paul Tyng