Wednesday, 10 October 2018

Knockout add to array of an array

I am looking for a way to add an item to an array that belongs to an item within another array using knockout and knockout mapping.

I have the following, a Person which has an array of WorkItems that has an array of ActionPlans. Person > WorkItems > ActionPlans

Knockout code is as follows -

var PersonViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, trainingCourseItemMapping, self);

self.addWorkItem = function() {
    var WorkItem = new WorkItemVM({
        Id: null,
        JobSkillsAndExpDdl: "",
        JobSkillsAndExperience: "",
        ActionPlans: [],
        PersonId: data.Id
        })
   self.WorkItems.push(WorkItem)
};

self.addActionPlan = function () {
    var actionPlan = new ActionPlanVM({
        Id: null,
        priorityAreaStage: "",
        goal: "",
        action: "",
        byWho: "",
        byWhen: ""
        WorkItemId: data.Id
    });
    self.ActionPlans.push(actionPlan);
};
}

Array mapping

var trainingCourseItemMapping = {
    'WorkItems': {
        key: function(workitem) {
            return ko.utils.unwrapObservable(workitem.Id);
        },
        create: function(options) {
            return new WorkItemVM(options.data);
        },
}
};
var actionPlanMapping = {
'ActionPlans': {
    key: function(actionPlanItem) {
        return ko.utils.unwrapObservable(actionPlanItem.id);
    },
    create: function(options) {
        return new ActionPlanVM(options.data);
    }
}
}

Array item mapping

var WorkItemVM = function(data) {
    var self = this;
    ko.mapping.fromJS(data, actionPlanMapping, self);
}

var ActionPlanVM = function(data) {
    var self = this;
    ko.mapping.fromJS(data, {}, self);
}

And within my view i want to have the following -

<tbody data-bind="foreach: WorkItems">
//body table html here
</tbody>

<tbody data-bind="foreach: ActionPlans">
//body table html here
</tbody>

Error

The error i am currently getting is -

Unable to process binding "foreach: function(){return ActionPlans }"

Which i guess makes sense as it cant access it via WorkItems...am i missing syntax here or am i missing a step to get the PersonVM to access ActionPlans via WorkItems...any help would be appreciated.



from Knockout add to array of an array

No comments:

Post a Comment