2

I have the following:

var CardViewModel = function (data) {
    ko.mapping.fromJS(data, {}, this);
    this.editing = ko.observable(false);
    this.edit = function() {
        debugger;
        this.editing(true);
    };

};


var mapping = {

    'cards': {
        create: function (options) {
            debugger;  // Doesn't ever reach this point unless I comment out the create method below
            return new CardViewModel(options.data);

        }
    },

    create: function(options) {
        //customize at the root level.  
        var innerModel = ko.mapping.fromJS(options.data);
        //debugger;
        innerModel.cardCount = ko.computed(function () {
            //debugger;
            return innerModel.cards().length;
        });

        return innerModel;
    }
};

var SetViewModel = ko.mapping.fromJS(setData, mapping);
debugger;
ko.applyBindings(SetViewModel);

When I run this, the 'cards' method never gets hit, so those edit properties in the CardViewModel aren't available. I can hit that debugger if I comment out the "create" method, but I need both. Any idea what's going on?

0

1 Answer 1

1

'cards' is not a valid Javascript variable name. Try something else without the single quotes.

You will also need to edit your CardViewModel code as this in the inner function refers to the inner function and will not see the knockout observable in the outer function.

var CardViewModel = function (data) {
    var self = this;
    ko.mapping.fromJS(data, {}, this);
    this.editing = ko.observable(false);
    this.edit = function() {
        debugger;
        self.editing(true);
    };
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Dave. I'm a bit confused about the 'cards' - I'm following the example here for defining the "children" subarray: knockoutjs.com/documentation/plugins-mapping.html In my case, 'cards' is an array. This method does get hit when I remove the 'create' method.
Jake, did this answer your original answer? I'm in a similar spot right now and removing the single quotes makes no difference. I can never use a create for a child object unless I remove the main create.
I don't understand why this is accepted. This is clearly part of the knockout syntax as noted by @JakeP. Also, nowhere in the modified CaredViewModel does it reference the mapping.

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.