Merging a new array of elements with an existing Nockoutout array causes binding errors

I have an observable knockout array populated with some initial values โ€‹โ€‹when the web page loads, and I want to add to the observable array using the splicing method when the user interacts with the page. The new elements that I am trying to add to the array have the same properties as the original elements in the array, but when I try to merge the new elements into an existing array, I get a knockout binding error, for example: " Error: Unable to parse bindings. Message : ReferenceError: ContactName not defined; Binding value: text: ContactName ". This error occurs even if the property in question exists in all elements of the new array. I am trying to splicing in a Knockout observable array, not the main array object, because I want the bindings to be updated automatically. The splicing code is as follows: vmContacts.Contacts.splice(vmContacts.Contacts().length,0,contactData2); .

I created an example of a violin here so you can see it in action: http://jsfiddle.net/ak47/pMFwe/ . You will see an error in the browser console when you click the "Add Contacts" button.

I would like to avoid a loop through an array of new objects, to do push () for each element that I need to add, where the splice should work, but it is not. Is this a known knockout problem, or am I doing something wrong? Thanks for the help!

+4
source share
2 answers

You are trying to pass contactData2 as the third parameter to Array.splice , but Array.splice does not support the array as the third parameter. See also the documentation .

So you need to write something like

 vmContacts.Contacts.splice(vmContacts.Contacts().length, 0, contactData2[0], contactData2[1], contactData2[2], contactData2[3]); 

Or you can use push along with apply to "merge" your two arrays:

 vmContacts.Contacts.push.apply(vmContacts.Contacts,contactData2); 

JSFiddle demo .

+7
source

You are not creating a view model with the observables in it, you are just parsing JSON in a direct JS object. Use the mapping plugin to do this:

 var contactData2 = ko.mapping.fromJSON(contactJSON1); 

Equally, I do not think that you can refuse to use the foreach loop to add each of them to the array:

 var contactData2 = ko.mapping.fromJSON(contactJSON2); ko.utils.arrayForEach(contactData2(), function(item) { vmContacts.Contacts.push(item); 
-1
source

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


All Articles