2

Let's say I have something like this in Knockoutjs

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

Javascript would be something like this:

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

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

Is it possible to add a "meta" under "Thor" or "Hulk"?

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".

1 Answer 1

1

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.

So, you would be able to call item.meta.push from within your handler.

Sign up to request clarification or add additional context in comments.

4 Comments

Hmmm, I have a fiddle here: jsfiddle.net/wenbert/tRRxh/21 - I am not able to add a meta to the parent. That will be my first step. The second step will be adding a meta to an existing object.
Hi, I have updated my original post to reflect the fiddle. I hope it makes more sense now.
If you are going to create your Person in that manner, then you would want the constructor function to pass the "meta" data through to its constructor as well. Since it is an array of meta objects, then you would probably want to initialize it with an array or create an empty observableArray and push it. Sample: jsfiddle.net/rniemeyer/tRRxh/32
Exactly what I was looking for the first step. I have marked your answer as correct and will come back for a follow-up. Second step will be passing the target object and then adding the meta into that. Based on your answer and comments, I think I know what to do now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.