Naor
Naor

Reputation: 24103

bind two arrays to each other using knockout.js

I have one ViewModel that contains two arrays: arr1 and arr2. I would like arr2 to contains exactly what the arr1 contains. How can I do that?

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
}

Upvotes: 1

Views: 121

Answers (2)

Ilya
Ilya

Reputation: 29721

If you want copy first array to second once you can crate copy of arrya, using function ko.toJS or ko.toJSON

var myViewModel = function() {
    this.arr1 = ko.observableArray([]);
    this.arr2 = ko.observableArray(ko.toJS(this.arr1)); 
}

if you want change second array each time, when first is changed use subscriber

var myViewModel = function() {
    this.arr1 = ko.observableArray([]);
    this.arr2 = ko.observableArray([]);
    this.arr2.subscribe(function(newValue) {
       this.arr2(ko.toJS(this.arr1));
    });
}

Upvotes: 1

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

If you want to store reference to array's elements use should unwrap observable:

var myViewModel = function() {
    this.arr1 = ko.observableArray([]);
    this.arr2 = ko.observableArray(this.arr1());
}

If want clone array use Slice function of array:

var myViewModel = function() {
    this.arr1 = ko.observableArray([]);
    this.arr2 = ko.observableArray(this.arr1.slice(0)); 
}

Upvotes: 3

Related Questions