简体   繁体   English

观察到的js副本的observableArray

[英]Knockout js copy of observableArray

How to make copy of self.items and place values in self.copy ? 如何制作self.items副本并将值放在self.copy I tried to do self.copy(self.items.slice()); 我试图做self.copy(self.items.slice()); but it does not work 但它不起作用

 function MyViewModel() { var self = this; self.items = ko.observableArray(); self.copy = ko.observableArray(); self.items.push({ id: 1, name: 'Jhon' }); self.items.push({ id: 2, name: 'Smith' }); self.copy(self.items.slice()); self.alarm = function (data) { var itemsWithSameId = self.copy().filter(function (item) { return item.id === data.id; }); var theItem = itemsWithSameId[0]; debugger; } } ko.applyBindings(new MyViewModel()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.0.0/knockout-min.js"></script> <table> <thead> <tr> <th>Passenger name</th> </tr> </thead> <tbody data-bind="foreach: items"> <tr> <td><input class="target" data-bind="value: name, event: { change: $root.alarm}" /></td> </tr> </tbody> </table> 

The problem is that when you copy an object, you're copying references rather than data. 问题在于,当您复制对象时,您是在复制引用而不是数据。 Using slice is good for dealing with arrays if the contents are not objects, but yours are. 如果内容不是对象,而是您的对象,那么使用slice可以很好地处理数组。

What you can do is use ko.toJS to make a deep copy (as long as you're just interested in comparing non-object members). 您可以使用ko.toJS进行深拷贝(只要您只想比较非对象成员)。

 function MyViewModel() { var self = this; self.items = ko.observableArray(); self.copy = ko.observableArray(); self.items.push({ id: 1, name: 'Jhon' }); self.items.push({ id: 2, name: 'Smith' }); self.copy(ko.toJS(self.items())); self.alarm = function (data) { var itemsWithSameId = self.copy().filter(function (item) { return item.id === data.id; }); var theItem = itemsWithSameId[0]; debugger; } } ko.applyBindings(new MyViewModel()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.0.0/knockout-min.js"></script> <table> <thead> <tr> <th>Passenger name</th> </tr> </thead> <tbody data-bind="foreach: items"> <tr> <td><input class="target" data-bind="value: name, event: { change: $root.alarm}" /></td> </tr> </tbody> </table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM