Question

I'm confused as to when and where I should declare my viewModel when using the mapping plugin.

Here's my json file:

{
    "members": [
        {
            "memberid": "001",
            "membername": "Jason"
        },
       {
            "memberid": "002",
            "membername": "Bob"
        }
    ]
}

Here's the html template:

<div data-bind="foreach: members">
<h3 data-bind="text: memberid"></h3>
<p>Name: <span data-bind="text: membername"></span></p>  
</div>

Here is the rest:

var data = $.getJSON("members.json",function(data)  
            {
                var viewModel = ko.mapping.fromJSON(data);
                 ko.applyBindings(viewModel);

            }
        );

ko.mapping.fromJSON(data, viewModel);

Thanks in advance for your assistance!

Was it helpful?

Solution

You likely want to declare your viewModel outside of the closure, so it is more accessible. For example:

var viewModel = {};
var data = $.getJSON("members.json",function(data)  
            {
                viewModel.model = ko.mapping.fromJSON(data);
                 ko.applyBindings(viewModel);
            }
        );

This would create the viewModel, make it accessible, and expose the model property (which would contain all the mapped data). You could skip the model property and just do it on the vm, too. You could even move the applyBindings outside of this, since you really only want that to run once.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top