Detecting change to Knockout view model

2019-01-12 18:02发布

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?

8条回答
爷、活的狠高调
2楼-- · 2019-01-12 18:26

I've adapted @Brett Green code and extended it so that we can have AcceptChanges, marking the model as not dirty plus having a nicer way of marking models as trackables. Here is the code:

var viewModel = {
    name: ko.observable()   
};

ko.track(viewModel);

http://jsfiddle.net/david_freire/3HZEu/2/

查看更多
放我归山
3楼-- · 2019-01-12 18:26

I did this by taking a snapshot of the view model when the page loads, and then later comparing that snapshot to the current view model. I didn't care what properties changed, only if any changed.

Take a snapshot:

var originalViewModel = JSON.stringify(ko.toJS(viewModel));

Compare later:

if(originalViewModel != JSON.stringify(ko.toJS(viewModel))){
    // Something has changed, but we don't know what
}
查看更多
登录 后发表回答