如何制作self.copy
的副本并将值放在self.copy(self.items.slice());
中?我尝试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>
&#13;
InstallDir
&#13;
答案 0 :(得分:2)
问题在于,复制对象时,您需要复制引用而不是数据。如果内容不是对象,那么使用slice
对于处理数组是有好处的,但是你的是。
您可以使用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());
&#13;
<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>
&#13;