find a location for property in a new city

Wednesday 18 April 2012

jQuery - Don't use bind and definitely don't use live!

If you use jQuery you have almost certainly used the .click(fn) event. You may know that just calls .bind('click', fn). You may have used live(). You may know that live() is weird and buggy and inefficient. You may have heard you should not use it in favour of .delegate(). You may have heard of the new .on(). But which is better? bind vs live vs delegate vs on?

Take the following html:

<div id="myContainer">
    <input type="button" id="myBtn" value="Click me!" />
</div>
<script type="text/javascript>
    $('#myBtn').click(doSomething);
</script>

I have a button that has a javascript function called doSomething attached to it. This works fine until I dynamically replace the inner HTML of the div myContainer with a new button (with same ID etc). doSomething will no longer be attached to the new myBtn button so it will not be called when the button is clicked.

FYI, $('#myBtn').click(doSomething); is just shorthand for writing $('#myBtn').bind('click', doSomething);

So you can change the JavaScript code above to $('#myBtn').live('click', doSomething); and it will still work even when the button is brought in or generated dynamically. Up until now I have found that the live function uses magic to just make it all work even after ajax abuse and therefore it is better.

However, recently (in a more complex implementation) I found it was causing some undesired behaviour so I had a dig into it. Turns out live() is buggy and badly performing and has actually been deprecated as of jQuery v1.7 so do not use live! What should you be using for this type of functionality then?

Well, delegate has been the popular replacement since it attaches the method once to a selected container but still targets the inner element as bind or click would. The importance is two fold:

  1. The functionality is not wastefully attached to each element matched and instead just once to the containing element
  2. Dynamically added items that match the selector will still fire the event since the event is not attached to this element, it is attached to the container that has remained static

In fact live does the same as delegate but it's containing element cannot be defined, it is the whole document which, if you have a deep DOM, finding the originating element using the selector could cause it to search a long way. Lame... In fact, I found bugs with it and there are other details which mean you should use delegate instead. I say should because there is a new cool kid on the block.

So what is better than bind, live and delegate?

You should use .on(). All the cool kids are doing it. Want me to name drop users of on? Well, ME! Perhaps more famous in the JavaScript world is jQuery, and they use it! If you look at the jQuery library bind, live and delegate all just call on as of jQuery v1.7+

So my JavaScript code above should change to:

Bind and click are still fine in my opinion as nice little shortcuts but only when using it them to attach a function to one specific element and only when you are not attaching to dynamic objects. If you are attaching to, say, multiple <li>’s in a <ul> you should use on() instead to attach the event to the <ul> and target the event to the <li>’s. This way there is only one function and multiple references to it rather than creating the function once for each of the <li>’s.

Follow britishdev on Twitter

50 comments:

  1. Nice information many thanks to the author. It is incomprehensible to me now but in general the usefulness and significance is overwhelming. http://scarprin.net/

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Bệnh viêm gan b lây qua đường nào ?Viêm gan B là căn bệnh lây lan lặng lẽ, tiến triển âm thầm do virus viêm gan B(HBV) gây ra, đây là một trong những bệnh được cảnh báo vô cùng nguy hiểm.
    Cách rửa mũi cho trẻ sơ sinhThời tiết thay đổi đột ngột rất dễ làm trẻ mắc các bệnh về mũi, họng. Lúc này, mẹ cần vệ sinh mũi cho bé thường xuyên để điều trị chứng viêm mũi, đồng thời phòng cách bệnh về đường hô hấp
    Dấu hiệu nhận biết người bị nhiễm hivNói suy giảm miễn dịch mắc phải có nghĩa là quá trình này xảy ra trong khoảng thời gian sống của con người, không phải do di truyền hay bệnh bẩm sinh của hệ miễn dịch.
    Mới bị nhiễm hiv có chữa được không?Để giúp các bạn hiểu rõ hơn về bệnh hiv, sau đây bài viết xin chia sẻ đến một số thông tin hữu ích về bệnh, cùng tìm hiểu nhé!
    Que thử thai hai vạch đậm có chính xácDùng que thử thai ngay tại nhà là biện pháp nhằm phát hiện hCG trong nước tiểu. Đây là hormone đầu tiên có mặt sau khi trứng thụ tinh nằm trong tử cung (khoảng 6 ngày sau thụ tinh)
    Dùng que thử thai chip chip có chính xác không?Thị trường que thử thai tại Việt Nam khá đa dạng. Phổ biến và thông dụng nhất với chị em phụ nữ là thương hiệu Quick Stick.
    Thụ tinh trong ống nghiệm là gì hết bao nhiêu tiền?Hầu hết chúng ta, nhất là những cặp đôi trẻ và khoẻ mạnh đều nghĩ rằng chúng ta có thể thụ thai tự nhiên và sinh con khi chúng ta muốn. Nhưng không phải lúc nào cũng đơn giản như vậy
    Bệnh thuỷ đậu phải kiêng những gì?Nếu không biết điều này, bệnh tình sẽ trở nên trầm trọng hơn, thậm chí có thể gây tổn thương thần kinh ung ương, ung thư da hay tử vong.
    Trẻ em bị bệnh thuỷ đậu nên ăn gì?Bệnh thủy đậu đang vào mùa và trẻ em là đối tượng dễ bị nhiễm bệnh nhất do khả năng miễn dịch yếu.
    Tuổi dậy thì của con gái là gì?Tuổi dậy thì là một giai đoạn quan trọng trong cuộc đời một con người, trong giai đoạn này có nhiều biến động về tâm sinh lý ở trẻ.
    Tác dụng của hạt sen tươi và hạt sen khôHạt sen là một thực phẩm được rất nhiều người yêu thích. Tuy nhiên, không phải ai cũng biết và khám phá hết những công dụng tuyệt vời của hạt sen.

    ReplyDelete
  4. Motifz Designer Lawn. 1, 2 & 3 Piece Unstitched Premium Embroidered Lawn 2019, Premium Lawn, Lawn 2019, Best lawn collection, Motifz, Best Lawn in Pakistan, Shipping worldwide. Stitching option available.

    ReplyDelete
  5. Wholesale printed custom perfume boxes with the highest quality and affordable prices. Free worldwide Delivery and free Custom Perfume Boxes design.

    ReplyDelete
  6. Buy online wholesale printed custom candle boxes and packaging at easy prices and shipping worldwide, with 24/7 customer support. Get a free custom quote now!!

    ReplyDelete
  7. Blackbird packaging provide you with any size, shape design, lipstick boxes sooner than any other packaging competitor in the market

    ReplyDelete
  8. Packaging town is a one stop solution for the short-run cbd face oil boxes, Wholesale Custom Boxes needs and supplies. At affordable prices. Request a free quote now.

    ReplyDelete
  9. Packaging town is a one stop solution for the short-run interlock boxes needs and supplies. At affordable prices. Request a free quote now.

    ReplyDelete
  10. Packaging town is a one stop solution for the short-run custom tuck boxes needs and supplies. At affordable prices. Request a free quote now.

    ReplyDelete
  11. Blackbird packaging provide you with any size, shape design,custom cookie boxes wholesale sooner than any other packaging competitor in the market

    ReplyDelete
  12. The post is absolutely fantastic! Lots of great information and inspiration both of which we all need! Also like to admire the time and effort you put into your blog and detailed information you offer! I will bookmark your blog!

    Love back Solution Specialist
    Vashikaran specialist  
    Love Vashikaran Specialist
    Vashikaran Specialist in Chennai Vashikaran Specialist in Jaipur  Vashikaran Specialist in Karnataka  Vashikaran Specialist in London UK  Vashikaran Specialist in Dubai  Vashikaran Specialist in Australia  Vashikaran Specialist in Punjab  

    ReplyDelete
  13. Blackbird packaging company can provide you with any size, shape design, and cookie packaging wholesale sooner than any other packaging competitor in the market

    ReplyDelete
  14. Clara Smith is a cheap essay writer, with years of experience and academic proficiency in the field of essay and
    Dissertation Writing Services. Also, she is an NGO activist and academic counsellor, hailing all the way from Birmingham, the United Kingdom.

    ReplyDelete
  15. Buy online sweatshirts for men from wild goat clothing. get free shipping

    ReplyDelete
  16. buy electronics online in lahore from alfatah at best prices. get free shipping

    ReplyDelete
  17. buy custom pillow boxes online from packaging town at best prices. Get Free shipping

    ReplyDelete
  18. buy business card boxes from packaging town at best prices. Get free shipping.

    ReplyDelete
  19. assignment help online where students can reach out to us with their queries at any point of the day or night and get the most effective solutions.

    ReplyDelete
  20. These services are known for their highly researched writing. Doing proper research for an assignment will help improve quality, but students can’t spend too much time on research every time. Academic Dissertation Writing Services thoroughly take care of this step and even provide plagiarism-free grammatically correct assignments, which will surely fetch you a high grade.

    https://education753626040.wordpress.com/2021/03/31/4-ways-you-can-avoid-plagiarism-in-your-assignment/

    ReplyDelete
  21. Shop from a wide range of Local and Imported variety of makeup removers online and makeup remover wipes from Al-Fatah. Shop from a diversified range of makeup removers and makeup remover wipes from all top brands. Buy the best for your skin. Avail Free Delivery on orders above 1000 PKR for selected cities in Pakistan.

    ReplyDelete
  22. Do you stuck with your real estate assignment help and want assistance? We help the students of mainly Australia, USA and UK who face problems in writing their all assignment help. We deal with all aspects of real estate and we have extended our helping hands to solve all the issues which the students come up against while dealing with an assignment. Our expert team deals with these issues efficiently through real estate assignment help. In such a circumstance, availing assignment help services from the best experts of the industry becomes the best option to cope with such challenging situations. You, as a student, cannot deny the importance of assignments/homework help services and valuable contribution in learning module concepts.
    Computer Network Assignment Help
    Contract Law Assignment Help
    epidemiology assignment help

    ReplyDelete
  23. Buy lawn collection 2021 online from Ilaha Clothing at best prices.get free shipping.

    ReplyDelete
  24. buy pret collection 2021 online from Ilaha clothing at best prices. Get free shipping.

    ReplyDelete
  25. Availing research paper writing service online can save you from poor grades and help you achieve your academic goals. However, finding the right writing expert can be a challenge for many.

    ReplyDelete
  26. Blackbird packaging provide you with any size, shape design, custom cookie boxes wholesale sooner than any other packaging competitor in the market

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. Are you feeling on the edge lately due to the number of assignments piling on your desk? Are you considering other options to complete your assignments on time? You can buy assignments online from Ireland to gain some peace of mind. We understand the pressures you have to go through in order to do well in class and to secure a good career for yourself.

    ReplyDelete
  29. It's not just about how to create the resume through resume builder, but also how to make it attractive to the employer. This free resume maker is easy to use and has the advantage of offering the best nursing resume . If you are looking foe cdr help to make cdr report Get online assistance for this By MyAssignmenthelp.com , Margins and with the help of online paper editor formatting are always important when it comes to result

    ReplyDelete
  30. Make Your Dream Of Achieving The A+ Come True QQI Assignment Help are the top choice of students in Ireland to help. all those who are struggling to do their assignments. It is the dream of every student to see the top grades on their report cards, and we assure you that we will help you to get it. Order your assignments to see how our writing experts work delicately in producing an assignment paper that is worthy of getting the top scores.
    for more information visit website-https://www.qqiassignments.com/

    ReplyDelete
  31. buy mesh bra for women online from Dshred at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  32. Dissertation writing is a task that needs extensive research and reading reference books to look for old statistics. In student life you have a lot to do so you don't have enough time for dissertation writing, it is a time when you need the help of Can Someone Do My Essay For Me.

    ReplyDelete
  33. If you are having trouble with academic assignments in Ireland, we can help you. Then don't worry; Ireland Assignment Help will provide you with the best assignment. Pay and get specialized experts from college. we are able to write your assignment in only 24 hours.

    ReplyDelete
  34. buy makeup online from alfatah at best prices delivered at your doorstep. get free delivery

    ReplyDelete
  35. Buy gym wear online pakistan from dshred at easy prices delivered at your doorstep. Get free shipping.

    ReplyDelete
  36. buy power joggers online from dshred at easy prices delivered at your doorstep. Get free shipping

    ReplyDelete
  37. buy power joggers online from dshred at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  38. buy sports bra online from Dshred at easy prices delivered at your doorstep. Get free shipping

    ReplyDelete
  39. buy crop top for girls online from dshred at easy prices delivered at your doorstep. Get free shipping

    ReplyDelete
  40. Buy gym trousers for men online from Dshred at best prices delivvered at your doorstep. Get free shipping

    ReplyDelete
  41. Buy men shorts online from ndure at best prices delivered at your doorstep. Get free shipping.

    ReplyDelete
  42. Buy men shoes online from Al-Fatah at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  43. Buy grocery online in Pakistan at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  44. Shop for a huge range kids strollers, nursing and feeding products, school essentials, carriers, online toys, clothing for boys, girls and babies at Al-Fatah, Pakistan's leading chain of departmental stores. Shop from a huge range of top brands for kids from Al-Fatah. Free Delivery on orders above 1000 PKR in selected cities

    ReplyDelete
  45. This comment has been removed by the author.

    ReplyDelete
  46. Use DRS Convert OST to PST Online tool to convert OST files into any other file format or email client. It is a power-packed tool that facilitates users with all the advanced functionality that is required for file conversion. This software is completely secure and maintains data integrity.

    ReplyDelete
  47. Borjan offers its customers the outstanding qulity lace up shoes for men in Pakistan. We have the best quality lace up shoes in Pakistan for the most affordable prices. Get Borjan’s amazing collection of lace up shoes for men online. Get your favorite shoes for men from Borjan to keep yourself in style and comfort at the same time.

    ReplyDelete
  48. The nights are slightly cool at the start of winter, but the days are still warm. In this scenario, we all seek for something that is weather appropriate both throughout the day and at night because you will most likely be out from morning to evening. When the sun is shining, the weather might be hot and humid, so the best option is to wear a light, breezy fabric that is slightly warm. Linen fabric is your best friend in these situations. Their winter dress designs are something worth buying as they offer both comfort and a sassy look.

    ReplyDelete
  49. When the temperature lowers and the wind picks up, you crave something cozy to keep you warm and safe. If you need to go out for a fun evening with your best friends, a day with relatives, or a formal lunch with professional colleagues under such conditions, you hunt for fashionable garments that will keep you warm. With the best winter suits for women, we've got you covered.
    This extensive choice of winter textiles are produced with the finest of detailing, charming patterns, and trendy colours to provide you with the appropriate seasonal hues. They have the best for everyone, from embroidered to unstitched, solid colours to bright designs.
    So, let's embark on a quest to find the best dresses for girls to slay the winter days!
    pakistani clothes online

    ReplyDelete