Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top