Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One thing you do get with <code>.each()</code> is automatic local scoping (because you are invoking an anonymous function for every object), which in turn means if you are creating even more anonymous functions/closures/event handlers/whatever on every iteration, you never have to worry about your handlers sharing a variable. That is, JavaScript doesn't act like other languages when it comes to local scopes, but because you can declare a variable anywhere, it can fool you sometimes.</p> <p>In other words, this is wrong:</p> <pre><code>var idx,el; for (idx = 0; idx &lt;someObjectArray.length; idx++){ el = someObjectArray[idx] el.someEventHandler(function(){ alert( "this is element " + idx); }); } </code></pre> <p>Whenever any of those objects invoke their "someEvent" after this loop (please note that this is made up), the alert is always going to say whatever was last assigned to <code>idx</code>, which should be (as of the time invoked) <code>someObjectArray.length</code>;</p> <p>To make sure you save the proper index, you have to declare a local scope, create a variable and assign to that variable for use.</p> <pre><code>var idx,el; for (idx = 0; idx &lt;someObjectArray.length; idx++){ el = someObjectArray[idx]; (function(){ var localidx = idx; el.someEventHandler(function(){ alert( "this is element " + localidx); }); })(); } </code></pre> <p>As you can see, that's as ugly as hell, but it should work. Each event handler gets its own copy of <code>localidx</code></p> <p>Now compare that to <code>.each()</code></p> <pre><code>$(someObjectArray).each(function (idx, el) { el.someEventHandler(function(){ alert( "this is element " + idx); }); }); </code></pre> <p>A lot simpler, isn't it?</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. 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