I’m trying to understand how I can have nested knockoutjs view models with a little fiddle that lists some items and on click of a button, it shows the details of that item. Then, I have a button that updates the Id property of each item by adding 15 to each ones but for a reason, they end up having all the same value at the end.
Can someone enlighten me?
Thanks!
It’s your
.Namecomputed property. The Id change works correctly.http://fiddle.jshell.net/Y3JXD/1/
The
itemin the closure was always the lastitemin the list after the first execution. Remember that the computed is updated any time the observable changes. So, the first time during setup, it worked fine asitemwas theitemfrom the loop. But, what was captured in the closure was justitem(the 15th item), not the one that was for that specific loop instance.Update: forgot about the second parameter to computed as suggested in a comment.
http://fiddle.jshell.net/Y3JXD/1/
Here’s another technique for wrapping the reference in a closure, and capturing the right
iteminstance (just as a demonstration for what needs to happen to capture the proper scope).