1

How can I pass value from observable to observableArray without reference? Any ideas.

PROBLEM

My problem is when I push value to multiple I expect that the value should be only 3. But when I update single to clear all values, multiple value is also updated.

var self = {};

self.multiple = ko.observableArray();
self.single = ko.observableArray();

self.single.push(3);

self.multiple.push(self.single());

self.single([]);

console.log(ko.toJS(self.multiple));    

ko.applyBindings(self)

See fiddle.

Update

Another clean for copying array value is using .slice(). See another question here and a demo here.

Community
  • 1
  • 1
jmvtrinidad
  • 3,347
  • 3
  • 22
  • 42

1 Answers1

2

What about this solution(JSON.stringify create string representation of object and JSON.parse then restore it, but reference is lost):

var self = {};

self.multiple = ko.observableArray();
self.single = ko.observableArray();

self.single.push(3);

//only this row was changed
self.multiple.push(JSON.parse(JSON.stringify(self.single())));

self.single.push(2);

console.log(ko.toJS(self.multiple));


ko.applyBindings(self)
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26