문제

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