Knockout JS 映射插件混乱
我很困惑在使用映射插件时应该何时何地声明我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能希望在闭包之外声明您的 viewModel,因此它更易于访问。例如:
这将创建 viewModel,使其可访问,并公开模型属性(其中将包含所有映射的数据)。您也可以跳过模型属性,直接在虚拟机上执行此操作。您甚至可以将 applyBindings 移到此之外,因为您实际上只想运行一次。
You likely want to declare your viewModel outside of the closure, so it is more accessible. For example:
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.