Knockout: find out what observable trigger calculations

I have an object with several observables. Is there a way in the calculation to find out what observed changes, so the observables fired the calculated one?

Thanks in advance Matthew

+4
source share
1 answer

Without the details of what you are trying to achieve, I will post this in the hope that this can help.

An easy way to track changes is to use the .subscribeobservable method that you want to track. Every time an observable is updated, this method fires.

self.myValue = ko.observable('initial value');

self.myValue.subscribe(function (item) {
    alert('myValue has changed to: ' + item);
});

itempassed to the subscription function is optional, so a new value can be used if necessary.

:

JSFiddle

JS:

var viewModel = function () {
    var self = this;
    self.firstName = ko.observable('Mod');
    self.lastName = ko.observable('dinu');

    self.valueChanged = ko.observable('');

    self.fullName = ko.computed(function () {
        var val = '';
        if (self.valueChanged() !== '') {
            val = ' (' + self.valueChanged() + ' Changed)';
        }

        return self.firstName() + ' ' + self.lastName() + val;
    });

    self.firstName.subscribe(function () {
        self.valueChanged('First Name');
    });

    self.lastName.subscribe(function () {
        self.valueChanged('Last Name');
    });
};

ko.applyBindings(new viewModel());

HTML:

<div>
    <label for="fname">First Name:</label>
    <input id="fname" data-bind="value: firstName" />
</div>
<div>
    <label for="lname">Last Name:</label>
    <input id="lname" data-bind="value: lastName" />
</div>
<hr />
<div>Hello <span data-bind="text: fullName"></span></div>
<hr />
<div>Value Changed: <span data-bind="text: valueChanged"></span></div>
+1

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


All Articles