使用 updateFromJS 在应该添加值时替换值 [英] Using updateFromJS is replacing values when it should be adding them

查看:19
本文介绍了使用 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.

后来,这种情况发生了:

Later on, this happens:

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 时,knockoutjs 会杀死一切?

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.

如果您正在进行增量更新,最好的办法是找到您需要更新的项目,然后完全替换它们或替换每个项目上的单独 observable.

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天全站免登陆