Knockout : find out which observable triggerred co

2019-04-07 15:36发布

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

1条回答
该账号已被封号
2楼-- · 2019-04-07 15:40

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>
查看更多
登录 后发表回答