How to access property on object in viewmodel from html code?

后端 未结 2 716
萌比男神i
萌比男神i 2021-01-26 16:58

I hava a viewmodel as follow :

define(
    [\'jquery\', \'knockout\', \'knockout.mapping\', \'data/data\', \'models/models\'],
    function ($, ko, mapping, data         


        
2条回答
  •  北海茫月
    2021-01-26 17:49

    I think the problem is that you are initially creating your viewmodel as an empty object, like this:

    var post = {};
    

    And then you are trying to update the viewmodel, like this:

    mapping.fromJS(result, {}, post);
    

    However, the documentation for the mapping plugin at http://knockoutjs.com/documentation/plugins-mapping.html seems to indicate that you should create the viewmodel like this:

    var viewModel = ko.mapping.fromJS(data);
    // or, in your case
    var post = ko.mapping.fromJS(result);
    

    Then, when you need to call the server to get updated data, you can do this:

    ko.mapping.fromJS(data, viewModel);
    // or, in your case
    ko.mapping.fromJS(result, post);
    

    The important thing to consider, which I think RP was driving at, is that you can't create the viewmodel until after you have the data.

提交回复
热议问题