Infinite loop when converting a knockout object to a regular JavaScript object

The Folliwing instructions provided in the documentation , I have the following presentation model:

var newContactViewModel = function () {
    var self = this;

    self.Name = ko.observable();
    self.Address = ko.observable();
    self.City = ko.observable();
    self.State = ko.observable();
    self.PostalCode = ko.observable();

    self.Save = function () {
        $.ajax({
            type: "POST",
            url: "/contact",
            data: ko.toJS(self), //infinite loop here
            success: state.OnSaved
        });
    };
};

When a method is called self.Save, an infinite loop occurs. Chrome reports an error like:

Uncaught RangeError: maximum call stack size

If I use ko.mapping.toJS(self)instead ko.toJS(self), then I get a slightly more open error, but has no error message:

infinite loop error

If I exchange ko.toJS(self)for something like { Name: self.Name(), Address: self.Address() /* etc */ }that, then everything will be fine. It seems to be trying to transform the method Saveand re-invoke the method as a result.

There is either a bug in KnockoutJS, or a problem when I use it. I would prefer the latter. Thoughts?

+5
1

. ko.toJS , . jquery , . , , .

Save, . , toJS, , . . , .

, ignore , 'Save', Save .

var data = ko.mapping.toJS(self, {
    ignore: ['Save']
});

, Save JS.

self.Save = function () {
    $.ajax({
        type: "POST",
        url: "/contact",
        data: self.ToData(),
        success: state.OnSaved
    });
};
self.ToData = function () {
    var data = ko.toJS(self);
    delete data.Save; // remove functions
    delete data.ToData;
    return data;
};

, . . , , , , , .

self.ToData = function () {
    return ko.toJS({
        Name: self.Name,
        Address: self.Address,
        City: self.City,
        State: self.State,
        PostalCode: self.PostalCode
    });
};
+14

All Articles