Detecting change to Knockout view model

后端 未结 9 2270
情歌与酒
情歌与酒 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:05

    Consider using Knockout-Validation plug-in

    It implements the following:

    yourProperty.isModified() - Checks if the user modified the value.

    yourProperty.originalValue - So you can check if the value really changed.

    Along with other validation stuff which comes in handy!

    Cheers

    0 讨论(0)
  • 2020-12-04 08:06

    Use extenders:

    ko.extenders.trackChange = function (target, track) {
        if (track) {
            target.isDirty = ko.observable(false);
            target.originalValue = target();
            target.setOriginalValue = function(startingValue) {
                target.originalValue = startingValue; 
            };
            target.subscribe(function (newValue) {
                // use != not !== so numbers will equate naturally
                target.isDirty(newValue != target.originalValue);
            });
        }
        return target;
    };
    

    Then:

    self.MyProperty= ko.observable("Property Value").extend({ trackChange: true });
    

    Now you can inspect like this:

    self.MyProperty.isDirty()
    

    You can also write some generic viewModel traversing to see if anything's changed:

    self.isDirty = ko.computed(function () {
        for (key in self) {
            if (self.hasOwnProperty(key) && ko.isObservable(self[key]) && typeof self[key].isDirty === 'function' && self[key].isDirty()) {
                return true;
            }
        }
    });
    

    ... and then just check at the viewModel level

    self.isDirty()
    
    0 讨论(0)
  • 2020-12-04 08:12

    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/

    0 讨论(0)
提交回复
热议问题