Using updateFromJS replaces values ​​when you need to add them

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

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

It works great. Later, the user can add an attachment and that there it will break. While it adds a new attachment to the mode and is displayed on the page, it deletes all previously loaded items in attachmentsModel.convAttachments .

In the future, 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" }] 

Hope this gives a clear walk if you don't let me know. Any ideas why knockoutjs kill everything when I use updateFromJS ?

0
source share
2 answers

ko.mapping.updateFromJS () expects you to get a complete list of items that were originally prepared using ko.mapping.fromJS (). Any items that are not in the original are considered removable, and any new items in updates are considered add-ons. Thus, currently, the mapping plugin will not allow you to do incremental updates this way.

If you are doing incremental updates, the best choice would be to search for the items you need to update, and either completely replace them, or replace individual observable data for each item.

+4
source

you can always try using

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

Although I'm not quite sure if this will update all bindings correctly, you may need to respond to the binding by calling

 ko.applyBindings(attachmentsModel) 
0
source

Source: https://habr.com/ru/post/910364/


All Articles