将新的项目数组拼接到现有的Knockout可观察数组上会导致绑定错误 [英] Splicing new array of items onto existing Knockout observable array causes binding errors

查看:48
本文介绍了将新的项目数组拼接到现有的Knockout可观察数组上会导致绑定错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当网页加载时,我有一个带有一些初始值的可剔除可观察数组,当用户与页面交互时,我想通过splice方法添加到可观察数组中.我要添加到数组中的新项目具有与数组中原始项目完全相同的属性,但是当我尝试将新项目拼接到现有数组上时,出现了敲除绑定错误,例如:"错误:无法解析绑定.消息:ReferenceError:未定义ContactName;绑定值:文本:ContactName ".即使所讨论的属性确实存在于新数组中的所有项目上,也会发生此错误.我正在尝试在Knockout可观察数组上进行拼接,而不是在基础数组对象上进行拼接,因为我希望绑定能够自动更新.拼接代码如下:vmContacts.Contacts.splice(vmContacts.Contacts().length,0,contactData2);.

I have a knockout observable array being populated with some initial values when the web page loads, and I want to add to the observable array via splice method as the user interacts with the page. The new items I'm trying to add to the array have the exact same properties as the original items in the array, but when I try to splice the new items onto the existing array, I get a Knockout binding error, ex: "Error: Unable to parse bindings. Message: ReferenceError: ContactName is not defined; Bindings value: text: ContactName". This error occurs even though the property in question does exist on all the items in the new array. I'm trying to do the splice on the Knockout observable array, not the underlying array object, because I want the bindings to update automatically. The splice code looks like this: vmContacts.Contacts.splice(vmContacts.Contacts().length,0,contactData2);.

我在此处创建了一个小提琴示例,因此您可以在操作中查看它: http://jsfiddle.net/ak47 /pMFwe/.单击添加联系人按钮,您将在浏览器控制台中看到错误.

I created a fiddle example here so you can see it in action: http://jsfiddle.net/ak47/pMFwe/. You'll see the error in the browser console when you click the Add Contacts button.

我想避免遍历新对象的数组对需要添加的每个项目执行push(),这是拼接应该起作用的地方,但事实并非如此.这是淘汰赛中的已知问题,还是我做错了什么?感谢您的帮助!

I'd like to avoid looping through the array of new objects to do a push() for each item I need to add, that's where a splice should work, but it's not. Is this a known issue in Knockout or am I doing something wrong? Thanks for the help!

推荐答案

您尝试将contactData2作为Array.splice的第三个参数传递,但是Array.splice不支持将数组作为第三个参数.另请参见文档.

You try to pass the contactData2 as the third parameter of Array.splice but Array.splice does not support an array as the third parameter. See also in documentation.

因此,您需要编写类似的内容

So you need to write something like

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

或者您可以将pushapply一起使用以联接"您的两个数组:

Or you can use push together with apply in order to "join" your two arrays:

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

演示 JSFiddle.

这篇关于将新的项目数组拼接到现有的Knockout可观察数组上会导致绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆