javascript - knockoutjs observable arrays -


to simplify issue having have come following example.

var viewmodel = function() { this.self = this;   self.test = ko.observablearray([]); self.test2 = ko.observablearray([]);   self.test2.push('1'); self.test.push({   'foo':self.test2() }); console.log('the following console.log should output object foo : [1]'); console.log(self.test());   self.test2.push('2'); self.test.push({   'foo2':self.test2() }); console.log('this console.log should have 2 objects, first 1 foo : [1] , second foo2 : [1,2]') console.log(self.test());  }; ko.applybindings(new viewmodel()); 

initially both arrays empty

test = [] test2 = [] 

then push '1' test2

test = [] test2 = ['1'] 

then push new object test equal current value of test2

test = [ { 'foo' : ['1'] } ] test2 = ['1'] 

and log current value of test check

we push '2' onto test2

test = [ { 'foo' : ['1'] } ] test2 = ['1','2'] 

and push new object onto test test2's current value

test = [ { 'foo' : ['1'] }, { 'foo2' : ['1','2'] }  ] test2 = ['1','2'] 

when said , done, console.log on js fiddle show expected (above) not happens @ all.

both console.logs show following values test (note 'foo' has '1','2' shouldn't)

test = [ { 'foo' : ['1','2'] }, { 'foo2' : ['1','2'] }  ] 

can explain behavior or how achieve desired functionality described?

jsfiddle: https://jsfiddle.net/xlp3jdr7/

self.test.push({   'foo':self.test2() }); 

this puts object (array) contained in self.test2 new object. objects passed reference in javascript, not copied, when modify object later, composite object going appear different.

one common way of getting (shallow) copy of array slice it:

self.test.push({   'foo':self.test2().slice(0) }); 

this behave expect, long array isn't composed of objects might change.


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -