![](/img/trans.png)
[英]How to map to an Array coming from server object using Knockout Mapping plugin and have some computed?
[英]How to map to an Array coming from server object using Knockout Mapping plugin in templates?
我在理解ko.mapping.fromJS和ko.mapping.toJS的工作方式時遇到了一些麻煩。 這里簡化了對我的問題的解釋:我有一個來自Server的Risk Array對象,該Risk數組具有Places數組。
出於某些奇怪的原因,在調用ko.mapping.FromJS之后,我的子Places數組被清除或隱藏,因此我的模板無法訪問其內容...我發現通過使用ko.mapping.ToJS可以訪問Places內容,但是這樣做似乎在添加項目后並沒有刷新我的模板!
我正在嘗試構建一個非常簡單的網格,為了簡化起見,我可以在該網格中向數組中的第一個Risk添加位置:
var FromServer = {"Risk":[{"SourceKey":0,"Places":{"Place":[{"SourceKey":1}]}}]}
var viewModel =
{
places : ko.mapping.fromJS(FromServer.Risk[0].Places.Place),
addPlace : function()
{
alert('Entering add place, places count:' + this.places.length);
this.places.push({SourceKey:"New SK"});
}
}
//If I leave this line it will update list but not refresh template
//If I comment it out it will show my Places array as empty!!!
viewModel = ko.mapping.toJS(viewModel)
ko.applyBindings(viewModel);
這是我的網格的示例HTML代碼:
<p>You have asked for <span data-bind="text: places.length"> </span> place(s)</p>
<table data-bind="visible: places.length > 0">
<thead>
<tr>
<th>SourceKey</th>
</tr>
</thead>
<tbody data-bind='template: { name: "placeRowTemplate", foreach: places}'></tbody>
</table>
<button data-bind="click: addPlace">Add Place</button>
<script type="text/html" id="placeRowTemplate">
<tr>
<td><input class="required" data-bind="value: $data.SourceKey, uniqueName: true"/></td>
</tr>
</script>
這是我的jsFiddle: jsFiddle示例
我的問題是:為什么我必須用ko.mapping.ToJS解開viewModel以便可以操縱子數組?在這種情況下如何刷新模板?
請幫忙!
您的代碼有些錯誤。 新的JSFiddle在這里:
您需要為places數組創建一個可觀察的數組,否則基因剔除將不知道何時更新。 方法調用是
ko.observableArray(arrayVar)
您不想在視圖模型上調用toJS。 這將取消所有可觀察對象的包裝,並使Knockout無法更新您的綁定
當引用一個可觀察數組時,您需要使用parens: viewModel.places()。length。
在FromServer對象中,Place對象包含一個數組,其中包含對象{“ SourceKey”:1}。 我假設您打算讓place對象具有一個名為SourceKey的簡單屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.