0
votes

I am working on an online form system, with forms that will need to be updated over time. I am using Knockout.js in conjunction with the Mapping plugin to accomplish this and it is working well.

One problem I am having, however, is that it seems to be refusing to save any properties on a ViewModel that weren't in the JSON object loaded from the database. For instance, if the ViewModel that was saved to the DataBase looked like this:

var viewModel = {
    prop1: ko.observable(""),
    prop2: ko.observable(""),
    prop3: ko.observableArray()
};

I initialize the "viewModel" variable to this prototype, and then load my JSON data from the server, ko.mapping.fromJSON(data, {}, viewModel); and this works as expected. Here is where my problem is; If my viewModel now has an extra property, like so:

var viewModel = {
    prop1: ko.observable(""),
    prop2: ko.observable(""),
    prop3: ko.observableArray(),
    prop4: ko.observableArray()
};

If I load JSON data created based on the firsts prototype, I can access this fourth property in the viewModel, adding and removing from the array and seeing it updated on the screen, but it will not save back to the database using ko.mapping.toJSON(viewModel). I'm gathering that is has something to do with the "ko_mapping_" properties that get assigned to the parts of the viewModel that were mapped using the mapping plugin. I apologize if this situation has been addressed before, but I could not find the answer.

I need to be able to update the prototype for the viewModel as its particular requirements could vary slightly over time. This could happen to any of my forms, so a generic solution would be fantastic!

Thank you.

1

1 Answers

0
votes

The Knockout mapping plugin will automatically create necessary objects and observables to model the JSON you feed it, so it's generally easier to just let it care of the view model, so it's always up to date with what you have on the server:

var viewModel = function (data) {
    var model = ko.mapping.fromJS(data);

    // any custom observables not present in the JSON here

    return model;
}