简体   繁体   English

使用Knockout.js将元素动态添加到嵌套列表中

[英]Add elements dynamically to the nested list using Knockout.js Issue

I'm using Knockout-3.2.0.js in mvc4 application. 我在mvc4应用程序中使用Knockout-3.2.0.js。 I have a list of FieldInfo class, which contains a list of itself. 我有一个FieldInfo类的列表,其中包含其自身的列表。 FieldInfo contains field_id, field_name, file_name and list. FieldInfo包含field_id,field_name,file_name和列表。 After doing some manipulation, my action returns a list to the view. 进行一些操作后,我的操作将列表返回到视图。 I setup everything in my view: 我在自己的视图中设置了所有内容:

 @{
      var initialData = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
 }
 LineItemFields = ko.observableArray(@initialData);

Observable array is initially a list which has a list itself. 可观察数组最初是一个具有列表本身的列表。 Everything works fine until the user clicks the Add button. 一切正常,直到用户单击“添加”按钮。 My add button in viewModel has the following: 我在viewModel中的添加按钮具有以下内容:

 addLineItem = function () {
                ko.utils.arrayForEach(ko.toJS(LineItemFields), function (item) {
                    item.LineItemValues.push({ "FieldValue": "0", "FieldID": 1})
                })
            }

LineItemFields is the main list which has 7 child (as an example) and those 7 child have a list each, requirement is to add a new element to the lists of those 7 children each. LineItemFields是具有7个子级的主列表(作为示例),而这7个子级都有一个列表,要求是向这7个子级的列表中添加一个新元素。 I tried debugging and everything went well but it still doesn't add the new row. 我尝试调试,但一切正常,但仍然没有添加新行。 Following is in template binding: 以下是模板绑定:

<script id="LineItemDataTemplate" type="text/html">
        <td data-bind="foreach: $data['LineItemValues']"><input type="text" data-bind="value: FieldValue, enable: $parent.isUpdatable" class="table-column" /></td>
</script>

<table>
    <tr data-bind="template: {name: 'LineItemDataTemplate', foreach: LineItemFields}"> </tr>
</table>

Q1: Does the inner lists have to be observable as their parent is? 问题1:内部列表是否必须像其父级一样可观察?
Q2: If not, What is wrong with the addLineItem function? 问题2:如果不是,那么addLineItem函数有什么问题?

As there is no answer up to date and i got it working so i thought to post an answer to benefit others. 由于没有最新的答案,而且我可以正常使用,因此我想发布答案以使他人受益。 I made the following changes to my viewModel. 我对viewModel进行了以下更改。

 //added the observableArray to each item in the parent list
 ko.utils.arrayForEach(LineItemFields(), function (item) {
                item.LineItemValues = ko.observableArray(item.LineItemValues);
            })

 //Removed ko.toJS(..) from LineItemFields and applied ()
 addLineItem = function () {
        ko.utils.arrayForEach(LineItemFields(), function (item) {
        item.LineItemValues.push({ "FieldValue": "0", "FieldID": 1});
    })
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM