当需要添加值时,使用updateFromJS替换值 [英] Using updateFromJS is replacing values when it should be adding them

查看:96
本文介绍了当需要添加值时,使用updateFromJS替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

var attachmentsModel = {
    convAttachments: ko.mapping.fromJS([])
};

$(function() {
    ko.applyBindings(attachmentsModel)
    refreshConvAttachments();
});

function refreshConvAttachments() {
    $.ajax({
        url: '/xxxxxxx/',
        success: function (dataJS) {
            // Send KO the data
            ko.mapping.updateFromJS(attachmentsModel.convAttachments, dataJS);
        }
    }); 
}

上面的AJAX调用返回:

The AJAX call above returns:

[{
    "title": "BillGates",
    "added_by": "xxx",
    "thumb": "urlhere",
    "id": 410,
    "link": "/link/410",
    "added_on": "2011-02-22T12:57:09-08:00"
}, {
    "title": "biz-stone",
    "added_by": "xxx",
    "urlhere",
    "id": 411,
    "link": "/link/411",
    "added_on": "2011-02-22T12:57:53-08:00"
}]

这很好.稍后,尽管用户可以添加附件,但附件已损坏.在将新附件添加到该模式并显示在页面上时,它会删除attachmentsModel.convAttachments中所有以前加载的项目.

This works fine. Later though the user is able to add an attachment, and that's where it's breaking. While it adds the new attachment to the mode, and displays on the page, it removes all the previously loaded items in the attachmentsModel.convAttachments.

后来,这发生了:

ko.mapping.updateFromJS(attachmentsModel.convAttachments, file);

Ajax返回:

[{
    "title": "eric_schmidt",
    "added_by": "xxx",
    "thumb": "xxxxxx",
    "id": 417,
    "link": "/link/417",
    "added_on": "2011-02-22T13:16:45-08:00"
}]

我希望可以清楚地进行介绍,如果没有,请告诉我.有什么想法为什么我使用updateFromJS时killoutjs会杀死所有东西?

I hope that gives a clear walk through, if not please let me know. Any ideas why knockoutjs is kill everything when I use updateFromJS?

推荐答案

ko.mapping.updateFromJS()希望您会收到最初使用ko.mapping.fromJS()准备的物品的完整列表.原始内容中缺少的所有项目均被视为已删除,更新中的任何新项目均被视为附加项.因此,当前映射插件将不允许您以这种方式进行增量更新.

ko.mapping.updateFromJS() expects that you are receiving the complete list of items that was originally prepared with ko.mapping.fromJS(). Any items that are missing from the original are considered to be deleted and any new items in the updates are considered additions. So, currently the mapping plugin will not allow you to do incremental updates in this way.

如果您要进行增量更新,最好的选择是找到需要更新的项目,然后完全替换它们或替换每个项目上的单个可观察物.

If you are doing incremental updates, your best bet would be to locate the items that you need to update and either replace them completely or replace individual observables on each item.

这篇关于当需要添加值时,使用updateFromJS替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆