我想使用knockout.mapping插件映射JSON數據,但是heirarcical JSON數據無法正確填充我的對象屬性,頂級加載正常,但不是孩子的'RootTarget'數據?使用knockout映射JSON無法填充類型定義的對象屬性
我在做什麼錯?
淘汰賽的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>
可以PLZ發佈的jsfiddle例子嗎?只是你的JSON數據和測試它作爲靜態數據 –
對不起,應該做的是,在弗里斯特地方複製。幸運@nevesv在他的回答下面發佈了一個小提琴。 – DIGGIDY