我正在尝试使用kickout.mapping插件映射JSON数据,但是,杂乱的JSON数据无法正确填充我的对象属性,顶层可以很好地加载,但子'RootTarget'数据可以加载吗?
我究竟做错了什么?
淘汰赛Javascript
var Query = function(json)
{
this.ID = ko.observable(0);
this.Name = ko.observable();
this.RootTargetID = ko.observable();
this.RootTarget = ko.observable();
var mapping = {
'RootTarget': {
create: function (args) {
return new QueryTarget(args.data, null);
}
}
};
ko.mapping.fromJS(json, mapping, this);
}
var QueryTarget = function(json, parent)
{
this.ID = ko.observable(0);
this.Name = ko.observable();
this.ParentID = ko.observable(0);
this.Parent = ko.observable(parent);
this.FilterID = ko.observable(0);
var mapping = {
'ignore': ["Parent"]
};
ko.mapping.fromJS(json, mapping, this);
}
var QueryModuleViewModel = function()
{
var json = {
"ID": 2,
"Name": "Northwind 2",
"RootTargetID": 2,
"RootTarget": {
"ID": 2,
"Name": "Customers",
"ParentID": null,
"FilterID": 2,
"Parent": null
}
};
this.QueryObj = new Query(json);
}
window.onload = function () {
ko.applyBindings(new QueryModuleViewModel());
};
的HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TypeScript Knockout Mapping Query Test</title>
<link rel="stylesheet" href="app.css" type="text/css" />
<script src="Scripts/jquery-2.0.2.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.2.1.debug.js" type="text/javascript"></script>
<script src="Scripts/knockout.mapping-latest.debug.js" type="text/javascript"></script>
<script src="my_js_query_test.js"></script>
</head>
<body>
<h1>TypeScript Knockout Mapping Query Test</h1>
<div data-bind="with: QueryObj">
<span data-bind="blah: console.log($context)"></span>
<p>Query Name: <input data-bind="value: Name" /></p>
<hr />
<p>Quick test of RootTarget Values</p>
<p>RootTarget.ID: <input data-bind="value: RootTarget.ID" /></p>
<p>RootTarget.Name: <input data-bind="value: RootTarget.Name" /></p>
</div>
</body>
</html>
最佳答案
因为您的RootTarget
被声明为函数的ko.observable
,所以您需要使用空的args ()
对其进行调用以获取其值并访问存储的对象。
因此,您只需要更改绑定并添加缺少的()
:
<p>RootTarget.ID: <input data-bind="value: RootTarget().ID" /></p>
<p>RootTarget.Name: <input data-bind="value: RootTarget().Name" /></p>
演示JSFiddle.
或者您可以在这里使用
with
绑定<p>Quick test of RootTarget Values</p>
<!-- ko with: RootTarget -->
<p>RootTarget.ID: <input data-bind="value: ID" /></p>
<p>RootTarget.Name: <input data-bind="value: Name" /></p>
<!-- /ko -->
演示JSFiddle.
它具有一些不错的优点:
您不必重复
RootTarget
with
自动打开可观察对象的包装,因此您只需编写with: RootTarget
即可,无需括号它适用于
RootTarget
值为null
或undified
的情况,因此它会隐藏输入,而原始解决方案RootTarget().ID
会引发空引用异常。关于javascript - 使用 knockout 映射JSON无法填充类型定义的对象属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17612550/