Knockout JS 映射插件混乱

发布于 2024-12-26 21:57:56 字数 811 浏览 0 评论 0原文

我很困惑在使用映射插件时应该何时何地声明我的 viewModel 。

这是我的 json 文件:

{
    "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);

提前感谢您的帮助!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花想c 2025-01-02 21:57:56

您可能希望在闭包之外声明您的 viewModel,因此它更易于访问。例如:

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

这将创建 viewModel,使其可访问,并公开模型属性(其中将包含所有映射的数据)。您也可以跳过模型属性,直接在虚拟机上执行此操作。您甚至可以将 applyBindings 移到此之外,因为您实际上只想运行一次。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文