Knockout js - Dirty Flag issue

2019-07-20 14:30发布

问题:

I am using Knockout Js for my view page. I have a requirement where if any editable field changes, I have to enable Save button else not. This is working nicely. My issue is I have checkboxes too for each row of item. These are observable items in my viewModel. What happens now is when I check or uncheck any checkbox, Knockout considers that as Dirty item and enables the Save button which I don't want.

How can I tackle this?

回答1:

I am not sure of the exact code that you are using for a dirty flag, but if it involves using ko.toJS in a dependentObservable like this, then there is a trick that you can use to have it skip some observables.

If you create an observable that is a property of a function, then ko.toJS will not find it.

Here are two examples (someFlag and anotherFlag):

function Item(id, name) {
    this.id = ko.observable(id);
    //create a sub-observable that the dirty flag won't find
    this.id.someFlag = ko.observable(false);
    this.name = ko.observable(name);
    this.dirtyFlag = new ko.dirtyFlag(this);

    //or similarly, place an observable on a plain ol' function
    this.forgetAboutMe = function() { };
    this.forgetAboutMe.anotherFlag = ko.observable(false);  
}

Sample here: http://jsfiddle.net/rniemeyer/vGU88/