Prabesh
Prabesh

Reputation: 373

How can i know change in knockout.js ViewModel just by change in its observable property?

I have a ViewModel in knockout.js for personal information. I want javascript to think that whole PersonViewModel is changed if just a single observable property in that model is changed.

I also have another ViewModel for address and i want the same for it. As an end user of program I want program to tell which view model is changed by change in any of the observable property.

I could use "subscribe" but that means i would have to subscribe every observable inside the view model and i don't want to do that. Figuratively, i want to subscribe the whole ViewModel instead of each observable inside it. What should i do?

function PersonViewModel() {
        this.firstName = ko.observable("John");
        this.lastName = ko.observable("Doe");
        this.middleName = ko.observable();
        this.userName = ko.observable("Johnny");
        this.dateOfBirth = ko.observable("12/12/2012");

    this.firstName.subscribe(function () {
        alert("fisrtName changed");
    });
}

 function AddressViewModel() {
        this.city = ko.observable("@Model.City");
        this.street = ko.observable("@Model.Street");
    }

var pvm = new PersonViewModel();
var avm = new AddressViewModel();
var pNode = $("#personal-information").get(0);
var aNode = $("#address-information").get(0);
ko.applyBindings(pvm, pNode);
ko.applyBindings(avm, aNode);

My HTML:

  <div id="personal-information">
        <input data-bind="value: firstName" type="text" >
        <input data-bind="value: lastName" type="text" >
        <input data-bind="value: middleName" type="text" >
        <input data-bind="value: username" type="text" >
        <input data-bind="value: dateOfBirth" type="text" >
     </div>

Any help will be appreciated. Thanks.

Upvotes: 1

Views: 1461

Answers (1)

Michael Best
Michael Best

Reputation: 16688

Knockout includes a ko.toJS function that "clones your view model’s object graph, substituting for each observable the current value of that observable, so you get a plain copy that contains only your data and no Knockout-related artifacts." If you call ko.toJS in a computed, that computed will update whenever any observable in the view model is changed.

var p = ko.computed(function () {
    return ko.toJS(pvm);
});
var log = ko.observableArray();
p.subscribe(function (value) {
    log.push("Person changed");
});

https://jsfiddle.net/mbest/ubLzwerp/

Also see https://stackoverflow.com/a/7850364/1287183

Upvotes: 2

Related Questions