0
votes

I am a newbie to Knockout Js, I am using Knockout Mapping Plugin to transform the JSON data I receive from server to UI Elements. I am able to load the contents properly for the first time, however subsequent changes to data does not update the UI at all.

My html file has this (whose visiblilty i control in script)

<div id="Results" style="font-family: Tahoma,Verdana,sans-serif;font-size: 10pt; visibility: hidden" >
    <form> 
        <h4>List of all Arguments</h4> 
        <ul data-bind="foreach: arguments"> 
        <li> Argument: <span data-bind="text: argumentName"> </span>: <input data-bind="value: defValue"/>  </li> </ul> 
    </form>
</div>

The javascript function has this code,

function displayArguments(data){
    var page=document.getElementById('Results');
    page.style.visibility='visible';
    var viewModel = ko.mapping.fromJS(data);
    ko.mapping.fromJS(data, viewModel);
    if(applyBindingsInvokedAlready == 0){
        // applyBindingsInvokedAlready is global default to 0
        ko.applyBindings(viewModel);
        applyBindingsInvokedAlready =1;
    }
}

Just wanted to mention that I have tried the following steps before posting this question

  1. Tried ko.mapping.fromJS(data, {}, viewModel);
  2. Tried ko.cleanNode(document.getElementById('Results'))
  3. As tried above, call ko.applyBindings(viewModel); only once.

I am lost! :(

Please help me figure out the mistake I am doing here. Thanks in Advance!

1

1 Answers

0
votes

The problem is you are over writing you existing vm when you should check if the vm is defined and if so do something like this

KnockoutJS and binding a single object to a viewmodel

var viewModel;
function displayArguments(data){
    var page=document.getElementById('Results');
    page.style.visibility='visible';
    if(!!viewModel){
        viewModel.prop1(data.prop1); // obviously prop1 is not what you use, I just dont
                                         know whats in your model
        viewModel.someObservableArray(data.someObservableArray);
    }else
    {        
        viewModel = ko.mapping.fromJS(data);
        ko.mapping.fromJS(data, viewModel);
        if(applyBindingsInvokedAlready == 0){
            // applyBindingsInvokedAlready is global default to 0
            ko.applyBindings(viewModel);
            applyBindingsInvokedAlready =1;
     }
}