简体   繁体   English

淘汰JS嵌套数组。 将项目添加到子数组

[英]Knockout JS nested arrays. Adding items to a child array

Let's say I have something like this in Knockoutjs 假设我在Knockoutjs中有类似的内容

<pre data-bind="text: ko.toJSON($data, null, 2)">
{
    "people":[
        {
            "name":"Thor",
            "meta":[]
        },
        {
            "name":"Hulk",
            "meta":[]
        }
    ]
}
</pre>

Javascript would be something like this: Javascript将是这样的:

function SuperheroViewModel() {
    var self = this;
    self.people = ko.observableArray();
    self.people.meta = ko.observableArray();

    self.people.push(new Person({name: 'Thor'}));
    //self.people.push(new Person({name: 'Hulk'}));

    self.addHero= function() {
        self.people.push(
            new Person({
                name: 'Wolverine'
            })
        );

        //self.meta.push(new Meta({sex: 'male'});
    }
}

ko.applyBindings(new SuperheroViewModel());
​

HTML HTML

<button data-bind="click: addHero">Add Hero With Meta</button>

Is it possible to add a "meta" under "Thor" or "Hulk"? 是否可以在“ Thor”或“ Hulk”下添加“ meta”?

I would first like to add the "meta" when a new parent item is inserted. 我首先要在插入新的父项时添加“元”。 The second step would be adding a meta to a target "hero". 第二步是将meta添加到目标“ hero”。

If you are calling addMeta from within the context of a person , then KO will pass the current data item as the first argument to your function. 如果您是在person上下文中调用addMeta ,那么KO将把当前数据项作为第一个参数传递给您的函数。

So, you would be able to call item.meta.push from within your handler. 因此,您可以从处理程序中调用item.meta.push

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

相关问题 Knockout.js向数组添加新项目 - Knockout.js adding new items to array 如何从嵌套数组中删除数组,循环遍历 arrays 的 rest。 然后循环遍历嵌套 arrays 的 1 值,全部在 vanilla js 中 - How to remove an array from a nested array, loop throug the rest of the arrays. And then loop throug 1 value of the nested arrays, all in vanilla js Knockout js - beforeRemove动画,同时将项目添加到可观察数组 - Knockout js - beforeRemove animation while adding items to observable array JS:比较数组并添加新项或删除数组中不再存在的项 - JS: Comparing Arrays and adding new items or removing items no longer in array 在基因敲除中显示嵌套数组 - display nested arrays in knockout.js Knockout.js向子元素添加属性 - Knockout.js Adding a Property to Child Elements 如何删除可观察数组内部的红色水果数组中的项目-Knockout.js - How to remove items in the red fruits array inside observable arrays - knockout.js 淘汰赛-将单击绑定到嵌套数组子元素 - Knockout - Binding click to nested array child element 如何将一个数组添加到另一个数组以创建一个数组数组。 (JS) - How can I add an array, to another array to create an array of arrays. (JS) Javascript 数组。 加法、减法和合计 - Javascript Arrays. Adding, subtracting and totaling
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM