Knockoutjs ObservableArray data refersh

79 views
Skip to first unread message

朱贝贝

unread,
Oct 11, 2017, 12:12:18 AM10/11/17
to KnockoutJS
Hi,

When I use Knockoutjs ObservableArray, I found out that there are something make me confuse.
for example.

var array1 = ko.observableArray(["1","2","3"]);

var arr2 = array1();
arr2.push("4") //this will change original array1 value.

arr2 = ["2","4"] //this will not change original array1 value.

what happened for these? arr2 is not reference to array1 value right? when value been change, knockoutjs will create a new object I think.

Or maybe, arr2 at first is reference to array1 value, only when set value(=) will create a new object?

appreciate if someone can help me for this...

Thanks,
Bei Bei

Michael Aird

unread,
Oct 11, 2017, 12:53:35 PM10/11/17
to KnockoutJS
In your example, think of arr2 as a pointer to an array in memory. 

when you do "var arr2 = array1();" you are pointing the variable at the underlying array from the observable array. you can then manipulate the contents of that underlying array with push, pop, sort, etc.

if you later do "arr2 = ["2","4"]" you are pointing arr2 at a completely new array, unrelated to the underlying array of the observable.

Also, this is fundamental javascript behaviour, nothing specifically to do with knockout.
Reply all
Reply to author
Forward
0 new messages