Using updateFromJS is replacing values when it should be adding them
Asked Answered
R

2

0

I have this code:

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

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"
}]

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 Returns:

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

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?

Retene answered 23/2, 2011 at 1:16 Comment(0)
C
4

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.

Crist answered 23/2, 2011 at 4:25 Comment(1)
Actually, updateFromJS() is kind of deprecated function. You should use ko.mapping.fromJS() with diferent attributes. This post probably will help: #11779131Gurglet
C
0

you could always try using

$.extend(attachmentsModel.convAttachments,ko.mapping.fromJS(dataJS));

Although i am not quite sure if that will update all the bindings properly, you might have to reply the binding by calling

ko.applyBindings(attachmentsModel)
Chamberlain answered 23/2, 2011 at 23:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.