我有一个包含两个数组的ViewModel:arr1
和arr2
。我希望arr2
包含arr1
包含的内容。我怎么能这样做?
var myViewModel = function() {
this.arr1 = ko.observableArray([]);
this.arr2 = ko.observableArray(this.arr1); //Doesn't work - I need to bind arr2 to changes in arr1
}
答案 0 :(得分:3)
如果要存储对数组元素的引用,请使用unwrap observable:
var myViewModel = function() {
this.arr1 = ko.observableArray([]);
this.arr2 = ko.observableArray(this.arr1());
}
如果想要克隆数组使用数组的Slice
函数:
var myViewModel = function() {
this.arr1 = ko.observableArray([]);
this.arr2 = ko.observableArray(this.arr1.slice(0));
}
答案 1 :(得分:1)
如果您希望将第一个数组复制到第二个一次,您可以使用函数ko.toJS
或ko.toJSON
var myViewModel = function() {
this.arr1 = ko.observableArray([]);
this.arr2 = ko.observableArray(ko.toJS(this.arr1));
}
如果您希望每次更改第二个数组,首次更改时使用订阅者
var myViewModel = function() {
this.arr1 = ko.observableArray([]);
this.arr2 = ko.observableArray([]);
this.arr2.subscribe(function(newValue) {
this.arr2(ko.toJS(this.arr1));
});
}