Detecting change to Knockout view model

后端 未结 9 2408
情歌与酒
情歌与酒 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 08:02

    You can subscribe to the properties that you want to monitor:

    myViewModel.personName.subscribe(function(newValue) {
        alert("The person's new name is " + newValue); 
    });
    

    This will alert when personName changes.

    Ok, so you want to know when anything changes in your model...

    var viewModel = … // define your viewModel
    
    var changeLog = new Array();  
    
    function catchChanges(property, value){
        changeLog.push({property: property, value: value});
        viewModel.isDirty = true;
    }
    
    function initialiseViewModel()
    {
        // loop through all the properties in the model
        for (var property in viewModel) {
    
            if (viewModel.hasOwnProperty(property)) { 
    
                // if they're observable
                if(viewModel[property].subscribe){
    
                    // subscribe to changes
                    viewModel[property].subscribe(function(value) {
                        catchChanges(property, value);
                    });
                }
            }
        }
        viewModel.isDirty = false;
    }
    
    function resetViewModel() {
        changeLog = new Array();  
        viewModel.isDirty = false;
    }
    

    (haven't tested it - but you should get the idea)

提交回复
热议问题