淘汰赛JS映射插件的困惑 [英] Knockout JS mapping plugin confusion

查看:85
本文介绍了淘汰赛JS映射插件的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于使用映射插件时应在何时何地声明viewModel感到困惑.

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

这是我的json文件:

Here's my json file:

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

这是html模板:

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

剩下的就是这里了

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!

推荐答案

您可能想在闭包之外声明viewModel,因此更易于访问.例如:

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);
            }
        );

这将创建viewModel,使其可访问,并公开model属性(其中将包含所有映射的数据).您可以跳过model属性,也可以在vm上进行操作.您甚至可以将applyBindings移出此范围,因为您实际上只希望它运行一次.

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.

这篇关于淘汰赛JS映射插件的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆