我正在用Knockout構建一個應用程序,並發現它非常有用。 雖然,我有一個獲得多維數組(對象)可觀察的問題。獲取多維數組(對象)在KnockoutJS中可觀察
目前我使用的結構如下:
self.form = ko.observableArray(ko.utils.arrayMap(initialData, function(section) {
var result = {
name : section.name,
code : section.code,
type : section.type,
fields: ko.observableArray(section.fields)
};
return result;
}));
它運作良好,但我無法得到它的工作,如果initialData是兩個以上的級別。 我想是這樣
self.form = ko.observableArray(ko.utils.arrayMap(initialData, function(block) {
var result = {
name : block.name,
code : block.code,
type : block.type,
sections: ko.observableArray(ko.utils.arrayMap(block.sections, function(section) {
var result = {
name : section.name,
code : section.code,
type : section.type,
fields: ko.observableArray(section.fields)
};
return result;
}))
};
return result;
}));
最終的陣列結構看起來不錯,但淘汰賽不更新DOM的時候我在做推部分陣列:
self.addField = function(section) {
field = {
code: uid(),
name: "New Field",
value: '',
type: section.type
};
section.fields.push(field);
};
我也嘗試了knockout.mapping。 js插件(這是一種正確的方法?)首先看起來不錯,但在上面的函數推入後,我的新字段元素不可觀察,只是對象。
插件doumentation說:
// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);
但我不知道這是我的情況。
如果任何人有任何想法,它將不勝感激。
謝謝。
UPD: 讓第一級和第二級可觀察是不成問題的,問題在於更深入。
這裏是initialData的例子:
var blocks = [
{
"name" : "",
"sections" : [
{
"name" : "Section 1",
"fields" : [
{
"name" : "Field A",
"type" : "checkbox",
"code" : uid()
}
]
}
]
}
];
HTML
<div data-bind='template: { name: tpl-form-field-checkbox, foreach: fields }'></div>
<button class="btn addField" data-bind="click: $root.addField">Add</button>
<script type="text/html" id="tpl-form-field-checkbox">
<input type="text" name="" value="<%= name %>" /> <br/>
</script>
如果可能的話,查看initialData的示例會很有幫助。 – janfoeh
另外,您可以發佈HTML數據綁定的摘錄嗎? – janfoeh
我已更新問題,謝謝。 – Pavel