Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You are running into a classic issue caused by closures in JavaScript. In your loop there is really only one variable named <code>myid</code>. The functions that you are creating when subscribing to each item all have access to that same <code>myid</code> variable. At the end of the loop it's value is 3, so when the handlers run they all report the value of that variable.</p> <p>There is a lot of reference out there for closures and scoping in JavaScript. For example, here is another SO question: <a href="https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example">JavaScript closure inside loops – simple practical example</a></p> <p>One way for you to handle this, is to not use the intermediate variable and ensure that your handler's run with the current item.</p> <pre><code>item.selected.subscribe(function () { console.log(this.id); }, item); </code></pre> <p>In this example, the second argument defines the value of <code>this</code> when the function runs. So, it will run with the correct item as the context and you can access its properties from <code>this</code>.</p> <p><a href="http://jsfiddle.net/rniemeyer/WV6g5/" rel="nofollow noreferrer">http://jsfiddle.net/rniemeyer/WV6g5/</a></p> <p>You could even use <code>item.id</code> in the second argument.</p> <p>As you pointed out below, you can certainly create a function that takes in your variable and have it return a function to create a closure around that specific value. </p> <pre><code>var subscriber = function(id) { return function() { console.log(id); }; }; ... item.selected.subscribe(subscriber(myid)); </code></pre> <p>In the context of Knockout, I think that it is more practical to deal with your data item and ensure that it is <code>this</code> when your handler runs.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload