Search code examples
javascriptknockout.jsbreezeknockout-validation

Extending a breeze js entity's property causes the changes to not be tracked


I am using Knockout-Validation to check that certain fields entered by the user are valid. I am extending properties on a breeze entity to do this. Below are my extensions:

var employeeInitializer = function (employee) {


        employee.FirstName = ko.observable().extend({ minLength: 2, required: true });
        employee.LastName = ko.observable().extend({ minLength: 2, required: true });
        employee.TargetRate = ko.observable().extend({ min: 0, required: true });

        var validation = ko.validatedObservable({
            firstName: employee.FirstName,
            lastName: employee.LastName,
            targetRate: employee.TargetRate
        });

        employee.isValid = ko.computed(function () { return validation.isValid() });
}
manager.metadataStore.registerEntityTypeCtor("Employee", null, employeeInitializer);

Now, when I make a change to either of these three fields, the changes are not tracked. If the user is editing an Employee, but decides to cancel their edit, then I should be able to call the line below in the View Model.

self.employee.entityAspect.rejectChanges();

However, the entityAspect does not have any changes tracked, even though there should be. If I remove the extensions from the properties, then all works fine. Any ideas why this is happening?


Solution

  • I can't think of a good reason to use KO validation with Breeze entities. Breeze entities already incorporate validation as explained here. You can also learn about it in Brian Noyes Pluralsight course on Breeze.

    I don't know enough about KO validation to explain how your extension of the observables with KO validation breaks Breeze change tracking. If I had to guess, I'd guess that the act of extension replaces the original observables with new observables that Breeze knows nothing about. Therefore, changes to these new observables are not propagated down to the Breeze backing store that lies at the heart of each entity; from an entity perspective, nothing has changed.

    I'm not saying that is the true explanation. I'm suggesting it is a possibility ... one you can verify by comparing the observable property returned by employee.FirstName before and after extension. I'm guessing they aren't the same.

    Whether true or not, I encourage you to abandon KO validation in favor of Breeze native validation.

    We welcome your thoughts on what KO validation is doing for you that Breeze validation is not.

    I have some suspicions but I want to hear what you have to say.