KnockoutJS Maximum Call stack size exceeded

2019-09-09 13:14发布

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()
};

2条回答
Evening l夕情丶
2楼-- · 2019-09-09 14:03

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-09-09 14:12

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");
};
查看更多
登录 后发表回答