How to update a JSON Object that is represented in a form

前端 未结 3 1652
刺人心
刺人心 2021-01-27 12:10

I have a JSON object that I used to create a form. This JSON object is parsed by KnockoutJS.

Now, when I modify the form, I want the JSON object to be updated according

相关标签:
3条回答
  • 2021-01-27 12:38

    Is there a simple way to map each JSON Object field to form items in KnockoutJS ?

    Yes, If I understand what you want to do correctly. As of now, the values in your view model are not observables and won't be updated automatically as the form values change. There is a plugin to handle this mapping.

    http://knockoutjs.com/documentation/plugins-mapping.html

    Example: Using ko.mapping

    To create a view model via the mapping plugin, replace the creation of viewModel in the code above with the ko.mapping.fromJS function:

    var viewModel = ko.mapping.fromJS(data);

    This automatically creates observable properties for each of the properties on data. Then, every time you receive new data from the server, you can update all the properties on viewModel in one step by calling the ko.mapping.fromJS function again:

    ko.mapping.fromJS(data, viewModel);

    Hopefully this helps.

    0 讨论(0)
  • 2021-01-27 12:47

    The simplest way to turn your json model into a usable knockout model is with the mapping plugin.

    Alternatively, you can manually copy fields from your json model into ko.observable members of your view model, which give you more control and lets you choose to skip read-only properties.

    0 讨论(0)
  • 2021-01-27 12:54

    If your Knockout ViewModel matches your form, you could just use the built in ks.toJSON()

    http://knockoutjs.com/documentation/json-data.html

    A better option, especially if your form is large or complex, is to use either the mapping or viewmodel plug-ins

    http://knockoutjs.com/documentation/plugins-mapping.html http://coderenaissance.github.io/knockout.viewmodel/

    0 讨论(0)
提交回复
热议问题