janmvtrinidad janmvtrinidad - 1 month ago 5
Javascript Question

KnockoutJS - passing observable values without reference

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.

Answer

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)