0

I have a viewModel which has this observableArray

(function () {
    function myItems() {
        var self = this;
        self.itemArray = ko.observableArray();
        somefunction() {...
}
var myViewModel = new myItems();

This observableArray will contain instances of this:

(function () {
    function item() {
        var self = this;
        self.name = ko.observable("some data");
        self.doStuff = function () {
            return "doing whatever";
        };
    }
    window.item = item
}());

I map my json into the viewModel

var json = '{"name":"my main property", "itemArray": [ { "name": "Bob" }, { "name" : "Fred" } ] }';

var myViewModel = new myItems();
ko.mapping.fromJSON(state, {}, myViewModel);

How do I tell the mapping that it must map itemArray using the item object? How do I create the link between item() and myItems()?

Here's a fiddle showing the issue http://jsfiddle.net/dexster/hLEMz/7/

2 Answers 2

1

Solution is to use the create callback of the mapping options

var mapping = {
    'itemArray': {
        create: function (options) {
            //add items to the items object here
            ...
Sign up to request clarification or add additional context in comments.

Comments

0

Well, once you've serialised it into JSON to store the state, you're back to the position you were in before you processed the JSON data to populate your view models in the first place.

Actually, that's the first issue you have, you are serialising the new viewmodel, if you serialise itemArray on the viewmodel, then you will have the data that you started with:

var unmapped = ko.mapping.toJSON(myViewModel1.itemArray);

Then, you can just pass that in to your addItems method:

myViewModel2.addItems(unmapped);

instead of mapping them.

Here's an updated jsFiddle

3 Comments

Thanks for this but my fiddle doesn't reflect my real code which also has many properties in the main viewmodel. I need to use mapping to populate these properties again. If I could solve this issue I could probably remove addItems() and use mapping for the initial population loading of my viewmodel data
I've edited the question and fiddle to better explain the issue
In that case, you need to use the create function map, as answered by Dex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.