KnockoutJS Maximum Call stack size exceeded

2019-09-09 13:54发布

问题:

I have this code:

self.EditItemPopup = function (something) {
    var temp = ko.mapping.toJS(something);
    //self.ItemToEdit = ko.mapping.fromJS(temp, EditItem, self.ItemToEdit);
    ko.mapping.fromJS(temp, EditItem,self.ItemToEdit);
    self.FindMatchingCategory(something.CategoryID());
    $("#editItemPopup").dialog("open");
};

self.FindMatchingCategory = function (categoryID) {
    ko.utils.arrayForEach(self.ViewModel().Categories(), function (categoryToFind) {
        if (categoryToFind.CategoryID() == categoryID) {
            self.ItemEditCategory(categoryToFind);
        }
    });
};

When self.EditItemPopup is called once everything works fine, but when it is called a second time I get this error: Uncaught RangeError: Maximum call stack size exceeded

Could someone tell me where the problem is?

Thanks!

EDIT:

EditItem mapping:

var EditItem = {
    ItemName: ko.validatedObservable().extend({
        required: {
            message: "Please enter an item name.",
            insertMessages: false
        }
    }),
    ItemCost: ko.validatedObservable().extend({
        required: {
            message: "Please enter a valid price.",
            insertMessages: false
        }
    }),
    CategoryID: ko.observable()
};

回答1:

As Tomas mentioned, your mapping looks wrong. Here is a potential solution. NOTE: I am making a few assumptions here as I cannot see all of your model.

Define a model for editing:

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

    self.ItemName.extend({
        required: {
            message: "Please enter an item name.",
            insertMessages: false
        }
    });

    self.ItemCost.extend({
        required: {
            message: "Please enter a valid price.",
            insertMessages: false
        }
    });
}

Modify the EditItemPopup function like this:

self.EditItemPopup = function (something) {
    var temp = ko.mapping.toJS(something);
    self.ItemToEdit(new EditItemModel(temp));
    self.FindMatchingCategory(something.CategoryID());
    $("#editItemPopup").dialog("open");
};


回答2:

ko.mapping.fromJS has signature: ko.mapping.fromJS(data, mappingOptions, viewModel);

However, in your case second argument does not look like mapping options. It looks like view model.