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!

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top