0
votes

A JSON string is received from the server and I am trying to custom map using the KO Mapping plugin, so that I can add validation using KO validation plugin.

There is a model object named Player which has a property named Trophies which is an array of objects.

// Business Objects
var myPlayer = function (player) {
this.ID = ko.observable(player.ID);
this.Name = ko.observable(player.Name).extend({required: true});
this.Rank = ko.observable(player.Rank);
this.Trophies = ko.observableArray(player.Trophies);
}

var myTrophy = function (trophy) {
this.Name = ko.observable(trophy.Name).extend({required: true});
this.Year = ko.observable(trophy.Year).extend({required: true});
}

I don't know how to call the myTrophy so that I can Custom Map the Trophies array along with validation.

//KO binding
var playerModel = ko.mapping.fromJSON(jsonString, mapping);
ko.applyBindings(playerModel);

// Mapping
var mapping = {
    'Player': {
        create: function (options) {
            var _player = new myPlayer(options.data);
            return _player;
        }
    }
}

Here is the jsfiddle

if you notice in jsfiddle, if I remove the Name property I get the validation message 'This is Required' similarly I would like to get validation message for Trophy Name and Year. Let me know if you need more details. Thanks

2

2 Answers

1
votes

There are several different ways to achieve this.

One approach is to use the arrayMap utility function to call your function for each entry in player.Trophies

 this.Trophies = ko.observableArray(ko.utils.arrayMap(player.Trophies, myTrophy));

Then change myTrophy to return an object

var myTrophy = function (trophy) {
  return { 
           Name:  ko.observable(trophy.Name).extend({required: true}),
           Year: ko.observable(trophy.Year).extend({required: true})
         }
  }
1
votes

You don't really need your myPlayer function (and myTrophy) here, because you will do what the plugin already does except for the validation.

You could do this:

// Mapping
var mapping = {
    'Name': {
        create: function (options) {
            return ko.observable(options.data).extend({ required: true });
        }
    },
    'Year': {
        create: function (options) {
            return ko.observable(options.data).extend({ required: true });
        }
    }
}

The plugin will match all properties Name and Year to add the validation to them.

Demo