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

52 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. You’ve written nice post, I am gonna bookmark this page, thanks for info. I actually appreciate your own position and I will be sure to come back here.
    Run4.co gswitch3.co Superfighters.co

    ReplyDelete
  5. 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
  6. Thanks for sharing such a nice piece of information to us. This is very knowledgeable for me. I am an assignment expert and I am offering law assignment services to students of Australia and all over the world.

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

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

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

    ReplyDelete
  10. 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
  11. Blackbird packaging provide you with any size, shape design, lipstick boxes sooner than any other packaging competitor in the market

    ReplyDelete
  12. 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
  13. mylar label bags in stock now. Ready made Cali pack designs. Fast Shipping at Your Supplies. Custom designs available

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

    ReplyDelete
  15. 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
  16. Blackbird packaging provide you with any size, shape design, cbd bath bomb boxes sooner than any other packaging competitor in the market

    ReplyDelete
  17. 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
  18. Blackbird packaging provide you with any size, shape design, custom cbd tincture boxes sooner than any other packaging competitor in the market

    ReplyDelete
  19. Blackbird packaging provide you with any size, shape design, bath bomb boxes wholesale sooner than any other packaging competitor in the market

    ReplyDelete
  20. Blackbird packaging provide you with any size, shape design, custom cbd tincture boxes sooner than any other packaging competitor in the market

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

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

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

    ReplyDelete
  24. 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
  25. 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
  26. 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
  27. Blackbird packaging company can provide you with any size, shape design, and wholesale cookie boxes sooner than any other packaging competitor in the market

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

    ReplyDelete
  29. Are you wondering where in the UK you can find reliable and efficient essay typer? If yes, then you are in the right place. At MyAssignmentHelp, we provide you with the best essays tailored just for you by our expert essay writers. Related Pages- Case Study Help  thesis help

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

    ReplyDelete
  31. Are you looking for coursework help online? We offer coursework assistance so that you can cope with them efficiently. Our experts take care of all the requirements like MBA Assignment help, Essay writing service and deliver you with an excellent coursework that is sure to impress your teachers. The best in the UK, we are an coursework writing service that offers online coursework help to students. We boast of writers who help you fulfill your commitments. With an experience of almost ten years in this field, we make sure that you achieve your academic goals. We provide programming help, resume builder All the Assignment and essay related help you can just say to "do my essay" ang get all the solution at MyAssignmenthelp.com.


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

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

    ReplyDelete
  34. 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
  35. 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
  36. Shop Men Zipper Hoodies in a wide range of colors and styles at Wild Goat. Winter Zipper Hoodies Collection in long and short hoodies in variety of colors is now available at Wild Goat. View our wide collection of men's zipper hoodies and stock up your wardrobe now. Prices of our zipper hoodies are too low to miss.

    ReplyDelete
  37. Shop from a wide range of Local and Imported variety of makeup removers 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
  38. 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
  39. Shop from a vast range of variety of imported and local stock of prams and strollers online from Al-Fatah. Get your hands on the new wide range of prams, strollers, baby toddler strollers and baby prams from all the top brands. Avail Free Delivery on orders above 1000 PKR for selected cities in Pakistan.

    ReplyDelete
  40. Blackbird packaging company can provide you with any size, shape design, and bath bomb boxes sooner than any other packaging competitor in the market

    ReplyDelete
  41. 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
  42. Buy lawn collection 2021 online from Ilaha Clothing at best prices.get free shipping.

    ReplyDelete
  43. Blackbird packaging company can provide you with any size, shape design, and bath bomb packaging sooner than any other packaging competitor in the market

    ReplyDelete
  44. I read this post your post so nice and very informative post thanks for sharing this post


    Brokerage Calculator

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

    ReplyDelete
  46. 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
  47. Blackbird packaging provide you with any size, shape design, custom cookie boxes wholesale sooner than any other packaging competitor in the market

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

    ReplyDelete
  49. There is a query in many students' mind that is My Assignment Help Reviews. When we try to choose any assignment help service for our papers, we always have a fear that whether it will be a genuine or not! Well, this is quite an obvious matter. However, considering a credible and amazing service as fraud is indeed sheer foolishness, isn't it? Many of the students do not hire the service thinking it is a fraud one. But, the reality is something else. My Assignment Help Review has been operating in this industry for almost 10 years. They are not only efficient but also experienced. What do you need more to call it a reliable service?

    If you check Essaycritics.com, you will get to see the magic that Myassignmenthelp Reviews has spread with their quality services. You can notice that every single student has given them a 5 star for their excellent service.

    Must Read: Myassignmenthelp.com review?

    You need to know the areas where Myassignmenthelp Review works at its best. Then, you can decide on your own that whether MyAssignmenthelp.com is fraud or not. Look at their best features.

    Affordable Price: - The charges of MyAssignmenthelp.com are the best in the market. This has been noticed in different reviews of myassignmenthelp.com that most of the students choose them because of the excellent price they offer. When you think that MyAssignmenthelp.com is fraud, think about the number of students, who have appreciated their services.

    Must Read: Myassignmenthelp.com reviews?

    4500+ expert writers:- If you check their website, you will get to know that they boast a team 4500+ writers from different academic subjects. It is huge. This mainly helps them serve students in terms of providing quality.

    No missing deadline record: - MyAssignmenthelp.com has no record of missing deadlines. They always deliver the work on time. This is one of the main reasons why students prefer MyAssignmenthelp.com over others.

    High quality paper: - The expert writers maintain the quality of the paper. As they know the whole process of writing the paper, they put all the efforts to complete the same. It has also been reviewed by the students in essaycritics.com that they not only write the paper but also proofread and edit the same. That is why; there is no scope for errors in the work.

    So, from now on, instead of thinking MyAssignmenthelp.com is fraud, choose them and explore various services they provide.

    Summary:- The article discusses about the wrong concept that MyAssignmenthelp.com is a fraud and shows that how they work for the benefits of the students.

    ReplyDelete