Search code examples
javascriptjsonknockout.jsknockout-mapping-plugin

Mapping a JSON object to part of a view model using KnockoutJS


I'm having trouble building a view model that is composed of some data from the server and some added manually.

I keep getting that m() is undefined from the code below: JSFiddle

function getServerData()
{
     var m = 
         {
             FlowID:5,
             Amount:120
         };
    return m;
}

var entity = getServerData();

var vm = 
{
    m: ko.mapping.fromJS(entity),
    x: ko.observable("additional prop")
};

ko.applyBindings(vm);

I'm trying to bind it as follows:

<input data-bind="value: x()" />
<input data-bind="value: m().FlowID" />
<input data-bind="value: m().Amount" />

Solution

  • The mapping plugin does not turn your object into an observable only its properties.

    So after the ko.mapping.fromJS(entity) call m won't be a ko.observable.

    So you just need to write:

    <input data-bind="value: m.FlowID" />
    <input data-bind="value: m.Amount" />
    

    Demo JSFiddle.

    If you want to make your original binding work, then you need to change your vm:

    var vm = 
    {
        m: ko.observable(ko.mapping.fromJS(entity)),
        x: ko.observable("additional prop")
    };