0

当我在视图中添加卡片时,我称之为:

innerModel.addCard = function() {
                // This just adds a card to the UI
                var card = new cardViewModel(addCardDto);
                innerModel.cards.push(card);
            }.bind(this);

这会在 UI 中添加一张空卡片并让用户输入一些信息。当他们单击“保存”时,我通过网络发送这个最低限度的包,将其保存在服务器端,然后返回一个更完整的对象。更新也是如此——我只发送需要的东西,然后取回一个完整的对象。这是我的cardViewModel:

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

        self.isNew = ko.observable(false);

        // If the card hasn't been created yet, it won't have a cardId
        if (typeof this.cardId === 'undefined') {
            this.isNew(true);
        }

        this.save = function() {
            // Implement API call here, one for POST, one for PUT.  For now: 
            // Currently just using a hard-coded piece of data 'cardDto' that mocks the result of an API call
            var result = new cardViewModel(cardDto);  // Problem is somewhere around here
            result.editing(false);
            result.isNew(false);
            debugger;
            // trying to re-assign the object to the result here, but it's not working.  No errors from javascript, just no activity when I click "save".
            self = result;
        };

    };

在我看来,我有:

<a data-bind="click: save">save</a>

这是以前的工作,当我的保存方法是这样的:

this.save = function() {
                // Implement API call here, one for POST, one for PUT.  For now: 
                this.editing(false);
                this.isNew(false);
     };

我究竟做错了什么?

我试过这个:

this.save = function() {
            // Implement API call here, one for POST, one for PUT.  For now: 
            // Currently just using a hard-coded piece of data 'cardDto' that mocks the result of an API call
            var result = new cardViewModel(cardDto);  // Problem is somewhere around here
            result.editing(false);
            result.isNew(false);
            debugger;
            // trying to re-assign the object to the result here, but it's not working.  No errors from javascript, just no activity when I click "save".

            ko.mapping.fromJS(result, {}, self); // NEW
        };

但是当我运行它时,chrome 没有任何错误或任何东西就死了,它只是说“Aw snap”。

编辑:我在 IE 中运行,我得到一个“调用堆栈大小超出错误”。现在钻进去...

4

1 回答 1

2

self = result将变量重新分配self给结果,它不会导致对象更新自身或其任何属性。没有什么特别之处self会改变 JS 分配的工作方式。

只需调用ko.mapping.fromJS(result, {}, this)即可更新对象。

于 2013-03-26T19:40:12.467 回答