Detecting change to Knockout view model

后端 未结 9 2405
情歌与酒
情歌与酒 2020-12-04 07:38

Sure this is a very easy question to answer but is there an easy way to determine if any property of a knockout view model has changed?

9条回答
  •  情书的邮戳
    2020-12-04 07:53

    Consider a view model as follows

    function myViewModel(){
        var that = this;
        that.Name = ko.observable();
        that.OldState = ko.observable();
        that.NewState = ko.observable();
    
        that.dirtyCalcultions - ko.computed(function(){
        // Code to execute when state of an observable changes.
    });
    }
    

    After you Bind your Data you can store the state using ko.toJS(myViewModel) function.

    myViewModel.Name("test");
    myViewModel.OldState(ko.toJS(myViewModel));
    

    You can declare a variable inside your view model as a computed observable like

    that.dirtyCalculations = ko.computed(function () {});
    

    This computed function will be entered when there is change to any of the other observables inside the view model.

    Then you can compare the two view model states as:

    that.dirtyCalculations = ko.computed(function () {
      that.NewState(that);
    
      //Compare old state to new state
      if(that.OldState().Name == that.NewState().Name()){
           // View model states are same.
      }
      else{
          // View model states are different.
      }
    

    });

    **Note: This computed observable function is also executed the first time when the view model is initialized. **

    Hope this helps ! Cheers!!

提交回复
热议问题