我的数据模型如下所示。
Module
Fields (ObservableArray)
Actions(ObservableArray)
Fields (?)
name (dyanmic from field list)
type (dynamic from field list)
selected (entered by user in UI)
模块是主要对象。 Fields和Actions是可观察的数组。每个操作下的字段列表需要具有更新的字段列表,并且还具有从UI捕获的附加属性。
应如何填充操作模型下的字段?每个操作下的字段列表将具有所选字段的唯一值。
我是否需要订阅字段ObservableArray并手动操作每个操作下的字段列表,还是有其他更好的方法吗?
答案 0 :(得分:3)
这就是我处理这种情况的方法
http://plnkr.co/edit/sWVqrFHdzWUXob42xS7Z?p=preview
的Javascript
var childObject = function(data){
var self = this;
//No special mapping needed here, the mapping plugin does it for us
ko.mapping.fromJS(data, {}, self);
this.Select = function(){
self.selected(!self.selected());
};
};
var parentObject = function(data){
var self = this;
//Map the object to myself, using the mapping object we made earlier
ko.mapping.fromJS(data, {}, self);
//Remap the actions column to observable's
this.Actions = ko.observableArray(_.map(self.Actions(), function(item){
return new childObject(item);
}));
};
var myViewModel = function(){
var self = this;
this.RootObject = ko.observable();
var objectData = {
"Fields": [1, 2, 3, 4],
"Actions": [
{
"name": "David",
"type": "string",
"selected": false
},
{
"name": "Nish",
"type": "string",
"selected": true
}]
};
this.Init = function(){
//Pass the object data to the parent object.
self.RootObject(new parentObject(objectData))
};
};
$(function(){
myApp = new myViewModel();
myApp.Init();
ko.applyBindings(myApp);
})
HTML
<div data-bind="with: RootObject">
<table>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Selected</th>
</tr>
</thead>
<tbody data-bind="foreach: Actions">
<tr data-bind="click: Select">
<td data-bind="text: name"></td>
<td data-bind="text: type"></td>
<td data-bind="text: selected"></td>
</tr>
</tbody>
</table>
</div>