JohnCC
JohnCC

Reputation: 615

Knockout.Mapping create mapping hook for simple JSON array

When using the knockout.mapping plugin for knockout.js I can customize the way items in a collection are created like this:-

var ItemModel = function (data) {
    ko.mapping.fromJS(data, {}, this);
    this.FooProperty = ...;
};

var mapping = {
    'Items': {
        create: function (options) {
            return new ItemModel(options.data);
        }
    }
}

this.Items = ko.mapping.fromJS(data, mapping);

This assumes that the data contains a property "Items" which contains a collection. But what if data is just a JSON array? How can I hook my creation function into items in the top level root of the incoming data?

From looking at the docs, it seems that keys in the mapping object can be property names of the data to act on, or they can be one of include, ignore, copy. From this, I can't see how achieve what I want, unless I wrap the incoming JSON into an object with a propery, map it, and then unwrap the result.

Upvotes: 1

Views: 1572

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

You can put a create function at the top level of your mapping object to deal with the root object:

Like:

var mapping = {
    create: function(options) {

    }
};

Alternatively, you can just pass it in like:

ko.mapping.fromJS({ Items: data });

But it sounds like maybe you were trying to avoid doing that.

Upvotes: 3

Related Questions