Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout : find out which observable triggerred computed

I have an object with multiple observables. Is there a way in a computed to know which observable changes, therefore which observable fired the computed?

Thank you in advance Matthew

like image 246
Moddinu Avatar asked Jul 15 '14 08:07

Moddinu


1 Answers

Without details of exactly what you are trying to achieve, I'll post this in the hope it might help.

A simple way to track changes is to use the .subscribe method on an observable you want to track. Each time the observable gets updated, this method will fire.

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

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

The item passed in to the subscribe function is optional, so you can use the new value if required.

Here's a simple example of it in use with a computed:

Sample 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>
like image 171
Tanner Avatar answered Sep 17 '22 00:09

Tanner