Search code examples
knockout.jsknockout-mapping-plugin

Options passed to create have invalid parent?


I'm trying to use Knockout.mapping in conjunction with Knockout.validation to create a simple validated view model. I came across the create function in ko.mapping and thought that would suit my needs but it seems that the options.parent property isn't set to what I'd expect:

This is the basic code that I'm using or you can see a JSFiddle.

var o = {
    test: {
        value: "bob",
        validation: "{ required: true; }"
    }
};
var mapping = {
    'value': {
        create: function (options) {
            console.log(options.parent === o.test);
        }
    }
};

var vm = ko.mapping.fromJS(o, mapping);

Am I doing something wrong, or is this a bug? My ultimate aim is I want to call something along the following lines in create:

create: function(options) {
   var result = ko.mapping.fromJS(options.data);
   if(options.parent.validation !== undefined) {
       result.extend(options.parent.validation); 
   }

   return result;
}

If this is just broken can anyone think of any relatively simple ways around the problem? The only solution I've come up with so far is a recursive property search to manually extend the observables which feels like a lot of unnecessary complexity.


Solution

  • What I did in my project was add an id to check the parent, like this:

    var o = {
        test: {
            id: "1",
            value: "bob",
            validation: "{ required: true; }"
        }
    };
    var mapping = {
        'value': {
            create: function (options) {
                console.log(options.parent.id() === o.test.id);
            }
        }
    };
    

    Test here