mattruma
mattruma

Reputation: 16687

Push new object into child property array of knockout object

I am trying to push a new object into a child object array on my knockout object ... and I keep getting an object is not a function error.

My script looks like ...

function PageViewModel() {

    var self = this;

    self.story = ko.observable();
    self.stories = ko.observableArray();

    self.addTask = function () {
         // this is where the error is occurring
         self.story().Tasks.push(new { IsDone: false, Description: 'Test description' });
    };

    self.getStories = function () {
        return $.ajax({
            type: 'GET',
            url: '@Url.Action("List", "Stories")',
            success: getStoriesSuccess
        });
    };

    function getStoriesSuccess(data) {
        var mapping = {};
        ko.mapping.fromJS(data.Stories, mapping, self.stories);
    }

    self.init = function () {
        self.getStories();
        ko.applyBindings(self);
    };
}

If I look at my knockout context in Chrome I see my Tasks property as Array[0]. All the non-Array properties work just fine.

Hoping I am just overlooking something easy!

Upvotes: 0

Views: 1931

Answers (1)

Andrey Nelubin
Andrey Nelubin

Reputation: 3294

It's not a knockout's error. Just try in console a = new {a: false, b: true} and you will get such error.

You must set:

self.story().Tasks.push(new Object({
    IsDone: false,
    Description: 'Test description'
)});

Upvotes: 2

Related Questions