Tuesday, April 6, 2010

Creating A Javascript Function Inside A Loop

I see the following question asked quite often in #javascript: "I loop over an array of elements and attach an event handler to each one. I pass along an index/variable for such & such reason. The problem is, when the event handler is executed, the index/variable is wrong!"

Example:

for (var i = 0, n = elements.length; i<n; i++) {
  var el = elements[i];
  el.addEventListener('click', function() {
    doSomethingWith(i, el); // i, el are not what you expect!
  }, false);
}

The reason that this is true is somewhat complex, but in basic terms, the function is only actually created once (instead of once each iteration of the loop) and that one function points to the last known values of the variables it uses. For more reading, start with closures and maybe move on to the ECMA Specification, in particular section 13.2, point 1.

The fix to this problem is not too difficult. There is a specific pattern that can be used to ensure that each iteration of the loop creates a brand-new function with the correct values. I call this pattern a "generator function". It probably has a proper name, but I'm not aware of it. The basic idea is to define a function (the generator) which creates and returns functions with the proper variables defined, and then call that generator function for each iteration of the loop, passing in the appropriate values. A typical generator function looks like this:

(function(variable) {
  return function() {
    // do something with variable 
  }
})(value);

There are a few things to notice in this pattern. First is that there are two function expressions: an outer one and an inner one. The outer one is the generator function, and the inner one is the function that contains your original code. Secondly, the generator function expression is wrapped in parenthesis and immediately called with an input of "value". This means that the inner function can use the identifier "variable" and it will refer to whatever value was passed in. The result of this whole shebang is a brand-new function which uses whichever values were passed in to the generator.

Applying this concept to our original problem, we come up with:

for (var i = 0, n = elements.length; i<n; i++) {
  var el = elements[i];
  el.addEventListener('click', (function(i, el) { 
    return function() {
      doSomethingWith(i, el);
    }
  })(i, el), false);
}

It's quite close to the original code, but with a little bit of wrapping. Note that this pattern can be useful for more than just attaching event handlers, although in most cases some form of loop is involved.

161 comments:

  1. hello,
    your explanation

    "but in basic terms, the function is only actually created once (instead of once each iteration of the loop) and that one function points to the last known values of the variables it uses. For more reading, start with closures and maybe move on to the ECMA Specification, in particular section 13.2, point 1."

    is incomplete, it doesn't explain the behavior for implementations that *do not* join objects.

    ReplyDelete
  2. Your "generator function" pattern saved my day. Thanks!

    ReplyDelete
  3. I just arrived to the same conclusion after an evening of thinking... but thanks for the finer solution (I just created manually 3 different functions for the 3 iterations I needed :p )

    ReplyDelete
  4. Many thanks for this trick !

    ReplyDelete
  5. Have been looking for this for years maybe! :D

    ReplyDelete
  6. thank you so much!

    ReplyDelete
  7. THANKS A LOT!!
    I can't believe it took me so long to find this - but it was worthwhile!
    I was struggling a lot, as I'm somewhat novice to javascript, and was writing in coffeescript..
    Btw, the (single-line) expression I came up with to do the same with coffeescript is:
    el.addEventListener('click', ((i,el)->->doSomethingWith(i,el))(i,el) for el,i in elements

    ReplyDelete
  8. You should avoid creating functions in loops. This is still creating a function, but it's one less per iteration.

    function something_wrapper(i, el) {
        return function() {
            doSomethingWith(i, el);
        }
    }
    var i,el; //for loops don't introduce a scope, best not to mislead people into thinking it does.
    for (i = 0, n = elements.length; i.>
        el = elements[i];
        el.addEventListener('click', something_wrapper(i, el), false);
    }

    ReplyDelete
  9. How could i get the sender and event type?

    ReplyDelete
  10. Thanks u, i have tried and i got the answer. It is awesome :)

    ReplyDelete
  11. The name is IIFE(Immediately Invoked Function Expressions)

    ReplyDelete
  12. Il Chelsea 16-17 terzo kit dispone di una combinazione di colori tradizionale in bianco e blu. Realizzato da Adidas, la nuova terza maglia del Chelsea 2016-2017 è stato rilasciato il 29 luglio ed è impostato per funzionare come Maglia nelle Coppe.maglie calcio 2017,
    maglie calcio poco prezzo, Maglia Deportivo prezzo a poco prezzo
    Maglia real madrid 2017 prezzo

    ReplyDelete
  13. This NFL Flag for Tennessee Titans is constructed of polyester, measures 3x5 feet, and has two metal grommets for attaching to our 6' aluminum flagpoles or any of our tailgate pole systems. The perimeter of our NFL Flag for Tennessee Titans is double stitched and the team logos are screen printed into the flag so they won't peel. Because of its large size, these flags are great to hang on any wall in your game room, sports room, garage.stars and stripes flags,
    football flags salebuy Cleveland Browns house divided flags
    Pittsburgh Steelers banners shop

    ReplyDelete
  14. I was reading your blog, This is really informative, Please keep me more update from your blog.

    ReplyDelete
  15. This blog is a great source of information which is very useful for me.

    Jual Obat Aborsi Pekanbaru

    Jual Obat Aborsi Bekasi

    Jual Obat Aborsi malang

    Jual Obat Aborsi

    Obat Aborsi semarang

    Obat Aborsi yogyakarta

    Obat Aborsi solo

    Obat Aborsi

    -Can be very slow but shows all backlinks along with their PR, Anchor and if it's a Nofollow

    ReplyDelete
  16. EFFING AWESOME! This was truly great find!

    ReplyDelete
  17. Liquidating checks, for instance, is a considerable measure less demanding these days than it was previously. 26 hours check cashing Chicago

    ReplyDelete
  18. Speaker or Volume button not working.
    our Site is very nice
    Thanks for Fantasctic blog and its to much informatic which i never think ..Keep writing and grwoing your self
    아바타카지노
    하이게이밍
    그래프사이트
    경마사이트
    슬롯게임
    슬롯게임
    https://ocn2001.com/

    ReplyDelete
  19. I am always searching online for articles that can help me. There is obviously a lot to know about this. I think you made some good points in Features also. Keep working, great job !

    Data Science Training

    ReplyDelete
  20. pinoybay are almost located in the whole world. So they love to watch these Pariwiki Tv Shows/ Pinoy Tv Replay on a daily basis.

    ReplyDelete
  21. GMA Network operates two National Pinoy TV Channel and Couple of Pinoy Radio channels. GMA TV is famous for Pinoy Television Shows, Pinoy Tambayan Lambingan, Pinoy Tambayan at Lambingan shows, Pinoy Tambayan shows.

    ReplyDelete
  22. 토토사이트추천
    was syndicated internationally and available on online as VOD through OTT platforms of Vo

    ReplyDelete
  23. internationally and available on online as VOD through OTT platforms of Vo
    파워볼게임

    ReplyDelete
  24. 먹튀검증
    cated internationally and available on online as VOD through OTT platforms

    ReplyDelete
  25. tionally and available on online as VOD through OT
    안전놀이터

    ReplyDelete
  26. MLB중계
    ternationally and available on online as VOD through OTT

    ReplyDelete
  27. i just love it what a work you done pinoy tambayan Visit our site

    ReplyDelete
  28. Freedom bra reviews for all boob sizes like push up bra freedom bra terpuge

    ReplyDelete
  29. an Hua, has been consistently entertaining its audience with interesting twists and turns in the lives of Ne
    https://www.pwball09.com

    ReplyDelete
  30. I got a web site from where I be capable of really obtain valuable information regarding my study and knowledge.
    Great Article… Good Job… Thanks For Sharing…

    Website:강남안마

    ReplyDelete
  31. Turkish Series with English Subtitles Watch latest episodes of Turkish Series and Turkish Dramas.
    Turkishsub is trying to bring subtitles to your favorite series and we need funds to forward to professional translators.

    ReplyDelete
  32. Electricity's extraordinary versatility means it can be put to an almost limitless set of applications which include transport, heating, lighting, communications, and computation.
    Electrician services Moose Jaw

    ReplyDelete
  33. That is a very good tip especially to those new to the blogosphere.
    Short but very accurate info… Appreciate
    your sharing this one. A must read post해외선물옵션

    ReplyDelete
  34. I am reading a blog on this website for the first time and I would like to tell you that the quality of the content is up to the mark. It is very well written. Thank you so much for writing this blog and I will surely read all the blogs from now on. I also write blog and my latest blog is QuickBooks File Doctor Download

    ReplyDelete
  35. ufa slot It’s remarkable to visit this web page and reading the views of all mates concerning this paragraph, while I am also zealous of getting experience.

    ReplyDelete
  36. Avoid all the common problems associated with removal services, especially when provided by overpriced companies.
    house removals Bolton

    ReplyDelete
  37. Current can consist of any moving charged particles; most commonly these are electrons, but any charge in motion constitutes a current.
    under floor heating Sunderland

    ReplyDelete
  38. How can I solve the Facebook not uploading video problem?

    If you're wondering why my video won't upload to Facebook, there are chances that your videos are larger than the Facebook limit or it doesn't have the right video format Facebook is using. Hence make sure to check if your video meets Facebook requirements. Once you're sure that your video meets Facebook's requirements, upload it again to see if the issue is fixed.

    Also Read

    how to disable facebook account
    canon printer not printing black
    yahoo mail not syncing
    yahoo mail not working on iphone
    how to turn off outlook notifications
    how can i speak with a live person at google
    spectrum ivr number

    ReplyDelete
  39. This was my first blog on your website. I would like to say that the quality of the content is up to mark. Thanks a lot for sharing this. I will surely read all the blogs from now.

    ReplyDelete
  40. I absolutely love your site.. Excellent colors & theme. Did you build this amazing site yourself? Please reply back as Iím planning to create my own personal blog and want to learn where you got this from or exactly what the theme is called. Many thanks! แทงบอลออนไลน์168

    ReplyDelete
  41. Whether you’re moving into a new home or looking to upgrade security at your current home,
    locksmith Bolton City Centre

    ReplyDelete
  42. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own Blog Engine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it. Anthony Dietrich

    ReplyDelete
  43. It is my first visit to your blog, and I am very impressed with the articles that you serve. Give adequate knowledge for me. Thank you for sharing useful material. I will be back for the more great post. ยูฟ่า168

    ReplyDelete
  44. Excellent website. I was always checking this article, and I’m impressed! Extremely useful and valuable info specially the last part, I care for such information a lot. Thanks buddy.
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

    ReplyDelete
  45. This is one of the best information i have read on internet. People should get lots of things from this.
    AWS Training in Hyderabad
    AWS Course in Hyderabad

    ReplyDelete
  46. I saw Your blog, It was a very nice blog, i am impressed for your blog content, your way is amazing thank you for share this information with us.
    Xfinity error code how to resolve

    ReplyDelete
  47. I am now not positive where you are getting your info, 홈카지노 however great topic. I must spend a while finding out more or working out more. Thanks for great information I used to be on the lookout for this information for my mission.

    ReplyDelete
  48. 카지노 Thank you so much for these information. You described it very well, keep it up. Wonderful, what a weblog it is! This blog provides useful data to us, keep it up .please visits once our website and get a free consultation..

    ReplyDelete
  49. 스포츠토토 I felt amazing reading this and I feel you are absolutely right. Inform me in the event that you are involved in garageband windows, that is my principal competency. I really hope to see you soon, bye for now!

    ReplyDelete
  50. 스포츠토토 Just a smiling visitor here to share the love (:, btw outstanding layout.

    ReplyDelete
  51. You completed certain reliable points there. I did a search on the subject and found nearly all persons will agree with your blog.
    한국야동

    ReplyDelete
  52. Great article! That kind of information is shared on the internet. Come and consult with my website. Thank you 카지노사이트

    ReplyDelete
  53. Running water, clay soil and father time can be a dangerous mix. The foundation of your house can not only be one of the more expensive fixes, but it can also be the most necessary. our site

    ReplyDelete
  54. After study a few of the blog posts in your web site now, and I actually like your means of blogging. I bookmarked it to my bookmark web site listing and will probably be checking back soon. Pls check out my website online as properly and let me know what you think. ufabet1688

    ReplyDelete
  55. Incredible! This blog lo?ks exactly ?ike my o?d one!
    It’s on a totally d?fferent subject b?t it ?as pretty muc?
    t?e ?ame layout ?nd design. Outstanding choice ?f colors!
    ライブカジノの

    ReplyDelete
  56. As a durable, economical, low maintenance solution for your home and business concrete driveways give a great impression from the street. Concrete contracting company

    ReplyDelete
  57. Excellent read, I just passed this onto a friend who was doing a little research on that. And he actually bought me lunch as I found it for him smile Therefore let me rephrase that: Thank you for lunch. 메이저사이트


    ReplyDelete
  58. I really appreciate the kind of topics you post here. Thanks for sharing us a great information that is actually helpful. Good day! ufabet

    ReplyDelete
  59. I accidentally searched and visited your site. I still saw several posts during my visit, but the text was neat and readable. I will quote this post and post it on my blog. Would you like to visit my blog later? 토토사이트순위


    ReplyDelete
  60. This was my first blog on your website. I would like to say that the quality of the content is up to mark. Thanks a lot for sharing this. I will surely read all the blogs from now. I also write blog and my latest blog is
    Quickbooks Font Size Too Small

    ReplyDelete
  61. I wan.ted to know about starting my web log.I think you have what you need to set up, and you have a blog.

    토토

    ReplyDelete
  62. Your ideas inspired me very much. 메이저토토사이트모음 It's amazing. I want to learn your writing skills. In fact, I also have a website. If you are okay, please visit once and leave your opinion. Thank you.


    ReplyDelete
  63. What a post I've been looking for! I'm very happy to finally read this post. 안전놀이터 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.


    ReplyDelete
  64. Hello, I'm happy to see some great articles on your site. Would you like to come to my site later? My site also has posts, comments and communities similar to yours. Please visit and take a look 토토사이트


    ReplyDelete


  65. Mehndi Hai Rachne Wali is Star Plus & Hotstar started newly launched Drama Serial
    Raghav puts necklace on Kirti, Kirti thanks Pallavi, Pallavi says thank Raghav

    Saath Nibhana Sathiya 2

    ReplyDelete
  66. Pinoy Channele bringing you best videos from all over Filipino entertainment, sports,
    news, politics, technology, music, covering all Latest Tv Replay Show of Pinoy Teleserye.

    Pinoy Teleserye

    ReplyDelete
  67. When I read your article on this topic, the first thought seems profound and difficult. There is also a bulletin board for discussion of articles and photos similar to this topic on my site, but I would like to visit once when I have time to discuss this topic. 안전토토사이트


    ReplyDelete
  68. I was impressed by your writing. Your writing is impressive. I want to write like you.안전놀이터 I hope you can read my post and let me know what to modify. My writing is in I would like you to visit my blog.


    ReplyDelete
  69. This is really interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your fantastic post. Also, I have shared your website in my social networks!
    I really liked your article post. Really looking forward to read more. Great.
    Say, you got a nice article. Really thank you! Fantastic.
    고스톱

    ReplyDelete
  70. It's perfect time to make a few plans for the future and it is time to be happy. I've learn this submit and if I may just I desire to recommend you some attention-grabbing things or advice. Maybe you could write subsequent articles referring to this article. I want to read even more issues approximately it!
    Also visit my web page : 스포츠토토

    ReplyDelete
  71. It's awesome in favor of me to have a web site, which is helpful designed for my know-how. thanks admin
    한국야동

    ReplyDelete
  72. Excellent site you've got here.. It's hard to find high-quality writing like yours nowadays. I seriously appreciate individuals like you! Take care!!
    토토사이트

    ReplyDelete
  73. Papers get to operate through Bible helpers and also plagiarism checkers to be certain that the author did not find idle at any stage in the process. Language inconsistencies won't be a thing with your newspapers as the specialists of our school paper writing support are passionate about writing and are always excited to strike you with something fresh. By: 먹튀검증사이트


    ReplyDelete
  74. Hello, I read the post well. 메이저토토 It's a really interesting topic and it has helped me a lot. In fact, I also run a website with similar content to your posting. Please visit once


    ReplyDelete
  75. This is the perfect post.메이저토토사이트 It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.


    ReplyDelete
  76. Yes, this is a good post without any doubts. You really do a great job. I inspired by you. So keep it up!! home builder Albany NY

    ReplyDelete
  77. Youre so right. Im there with you. Your weblog is definitely worth a read if anyone comes https://blogfreely.net/chanvaicalnaks/apples
    throughout it. Im lucky I did because now Ive received a whole new view of this. 메이저사이트추천

    ReplyDelete
  78. Thank you for some other informative blog. Where else could I get that type of information written in such an ideal means? I have a mission that I’m just now working on, and I have been at the look out for such information. 먹튀검증 It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.


    ReplyDelete
  79. Its most noticeably awful piece was that the product just worked discontinuously and the information was not exact. You clearly canot go up against anybody about what you have found if the data isn't right. ufa168

    ReplyDelete
  80. Thank you so much for such a well-written article. It’s full of insightful information. Your point of view is the best among many without fail.For certain, It is one of the best blogs in my opinion. 먹튀검증


    ReplyDelete
  81. Oh, the data you've shared in this incredible article is just magnificent. I am definitely going to make more use of this data in my future projects. You must continue sharing more data like this with us. 메이저놀이터


    ReplyDelete
  82. This is the type of information I’ve long been trying to find. Thank you for writing this information. https://www.concretecontractorssanjose.com/nearme-saratoga-concrete-contractors.html

    ReplyDelete
  83. It has a good meaning. If you always live positively, someday good things will happen. 메이저사이트Let's believe in the power of positivity. Have a nice day.


    ReplyDelete
  84. After looking into a few of the blog posts on your site, I seriously appreciate your way of blogging. 파워볼

    ReplyDelete
  85. Your skill is great. I am so grateful that I am able to do a lot of work thanks to your technology.메이저사이트 I hope you keep improving this technology.


    ReplyDelete
  86. Very helpful advice on this article! It is the little changes that make the biggest changes. Thanks a lot for sharing! 카지노사이트

    ReplyDelete
  87. This blog is a great source of information which is very useful for me. Thanks for sharing these information with all of us. whatsapp mod

    ReplyDelete
  88. Thanks for the blog filled with so many information. Stopping by your blog helped me to get what I was looking for. Now my task has become as easy as ABC. 안전놀이터


    ReplyDelete
  89. Nice blog. it is very good java script, valuable and helpful informative for me. Thanks for sharing these information with all of us. whatsapp mod

    ReplyDelete
  90. Thank you a bunch for sharing this with all of us you actually realize what you are talking about! Bookmarked. Please also seek advice from my site =). We could have a hyperlink change contract between us 안전놀이터


    ReplyDelete
  91. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article :D 먹튀검증


    ReplyDelete
  92. A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post.

    ReplyDelete
  93. Watch Turkish Series with English Subtitles Free Download

    Turkish 123

    ReplyDelete
  94. Star Star Plus Hindi Desi Serials Watch Online Hotstar Official Video. Latest Updates Enjoy full episodes Yeh Rishta Kya Kehalta Hai live.


    Kabhi Kabhie Ittefaq Sey

    ReplyDelete
  95. PINOY Flix Tv Tambayan
    PINOY Teleserye
    PINOY Lambingan
    Watch video pinoy tv shows online for filipino peoples, online full Episode
    Watch all your favorite Pinoy TV shows online for free! Our website can provide you with free PinoyTv Full Episode of pinoy tambayan or Lambingan and My Husband in law january 14 2022
    La Vida Lena january 14 2022
    Mano Po Legacy january 14 2022
    Ang Probinsyano january 14 2022

    ReplyDelete
  96. A variety of bachelor party cake for bride and groom available in various designs and affordable price. Free delivery in Delhi, Gurgaon.

    ReplyDelete
  97. Anytime Cakes offer 6 month birthday cake online in various designs and flavours. Shop top 6 month cake design for your little boy and girl online at the best price.

    ReplyDelete
  98. Order fondant cake online from DoorstepCake at a low price for all occasions like birthday, anniversary, etc. We offer free home delivery. Order now!

    ReplyDelete
  99. ty contiguous
    파워볼사이트 positions, regardless of whether they're in businesses that aren't obviously climate related. Mia Brown, a

    ReplyDelete
  100. I really loved reading your blog. It was very well authored and easy to undertand. Unlike additional blogs I have read which are really not tht good. I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well. พนันบอลออนไลน์

    ReplyDelete
  101. Гадание позвонит сегодня это попытка предсказать будущие события всегда заманивал человека. Гадание дает просмотреть, что вас ожидает в предстоящее время. Каждый порывается знать собственную судьбу и видит определенные виды хиромантии наиболее действенными.

    ReplyDelete
  102. great issues altogether, you just received a emblem new reader. What may you recommend in regards to your submit that you made a few days in the past? Any certain? เล่นสล็อตxo

    ReplyDelete
  103. Las Vegas' Wynn Casino - JTM Hub
    Casino. Wynn is a $4 billion jancasino.com resort with four hotel towers with 5,750 rooms deccasino and suites. febcasino Each of www.jtmhub.com the hotel towers includes a 20,000 square foot casino herzamanindir.com/ and a

    ReplyDelete
  104. 메이저사이트April 16, 2022 at 5:15 AM

    It has a good meaning. If you always live positively, someday good things will happen. 메이저사이트Let's believe in the power of positivity. Have a nice day.


    ReplyDelete
  105. DramaCool is korean tv kshow123 website which provides latest
    Korean drama, movies, Kshow and kissasian dramas with english
    subtitles online free in hd quality. DramaCool for everyone!


    Dramacool

    ReplyDelete

  106. I'm writing on this topic these days,
    블랙잭사이트

    This post is really magnificent.
    블랙잭사이트

    ReplyDelete
  107. Otakudesu Watch and Download Batch dan Streaming Anime Subtitle Indonesia resolusi 1080p at Otaku Desu format Mp4 dan MKV Lengkap. Otakudesu

    ReplyDelete
  108. AnimeDao Watch subbed anime online episodes with subtitles in high quality with tablet mobile or pc at AnimeDao AnimeDao

    ReplyDelete