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

85 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
  50. You can also get Programming help from our experts if you are facing difficulty while doing programming.

    ReplyDelete
  51. Do you come across challenges whenever you work on your thesis? Have you become frustrated? You need thesis help or assistance from experts. Hire our scholars and get rid of all your worries. If you are in the dilemma of whether it’s right to avail of professional help, then you should stop thinking too much.
    Related Pages -
    rewrite this for me
    law dissertation help
    case study help
    Cheap Essay Writer

    ReplyDelete
  52. Get Essay Topics easily with the help of our professionals and experts and fulfil all your needs for essay writing on all topics.

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

    ReplyDelete
  54. Thanks for sharing information with us…satisfied after visiting your blog…. Learn the latest trends & their practical application by experts with us…you can contact us click on
    Visit ISMT India

    ReplyDelete
  55. 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
  56. Calculate your integrals with the help of integral calculator online with the help of top experts and solve all your integral related query.

    ReplyDelete
  57. 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
  58. 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
  59. buy mesh bra for women online from Dshred at best prices delivered at your doorstep. Get free shipping

    ReplyDelete
  60. 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
  61. Hi, I am Charles a tutorial expert. If you have any question related to academics, and assignment help, then you can connect with me for a solution.
    I am a computer science assignment help expert and tenured dissertation writer, associated with the digital platform Myassignmenthelp. I’m also a sports enthusiast and travel blogger.
    Charles Joye is an experienced content writer with a passion for global assignment help. He is a passionate content marketer with years of experience in writing, he makes the best use of his skills and knowledge to express ideas in his write-ups. We offer academic writing services . to students all across the globe. You just need to choose your writer from a team of experts and let your essay assignment done on-time. Get 24X7 help online. It's time you should look for help from a dependable online specialist organization.
    Hi, I am Charles Joye an essay writing expert and tenured dissertation writer, associated with the digital platform allessaywriter.com. I’m also a sports enthusiast and travel blogger. Visit us: essay writer.

    ReplyDelete
  62. 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
  63. buy makeup online from alfatah at best prices delivered at your doorstep. get free delivery

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

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

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

    ReplyDelete
  67. Hi, I am Thomson a tutorial expert. If you have any question related to academics, and assignment help, then you can connect with me for a solution.
    I am a computer science assignment help expert and tenured dissertation writer.
    Ron Thomson is an experienced content writer with a passion for global assignment help. He is a passionate content marketer with years of experience in writing, he makes the best use of his skills and knowledge to express ideas in his write-ups. We offer academic writing services . to students all across the globe. You just need to choose your writer from a team of experts and let your essay assignment done on-time. Get 24X7 help online. It's time you should look for help from a dependable online specialist organization.

    ReplyDelete
  68. buy gym bottoms online from dshred at easy prices delivered at your doorstep. get free shipping

    ReplyDelete
  69. NDURE brings you its wide range of Men's t-shirt. Now you can buy your favorites with just a tap. You can find our t-shirts online by logging into our site. Our shirts are made with pure fabric that makes you stand out. So don't wait around and shop from our collection of online t-shirts.

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

    ReplyDelete
  71. Buy the latest Luxury Chiffon Collection 2021 from Reign and enjoy the best price with free home delivery.

    ReplyDelete
  72. There is no denying that the demand for report writing helphas increased significantly in the past few years. If you are one of those students who often rely on online experts visit us. In order to excel in mba dissertation writing services, you need to have knowledge of all the relevant concepts. You may need Coursework writers, but you start learning about the different ways to solve an essay, assignment once you have knowledge of different formats.

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

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

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

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

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

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

    ReplyDelete
  79. 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
  80. GotoAssignmentHelp is one of the most popular fields of study these days. Every year we Fulfilling all Physics homework help from scratch is must-do for every expert, new and already-established alike. Meeting deadlines and staying open to communicating with a customer is another pillar of Our Homework Help writing policy. We hand-pick the best candidates among those seeking accounting assignment help UK team.

    ReplyDelete
  81. Get assignment help. Most students could do with the Australia assignment help There is a reason. Your thoughts may be in order but when it comes to translating them to words on paper that have a flow and consistency as well as perfect grammar, this is beyond most students. Expert writers can do it effortlessly but for students it is not an easy task. In such cases you can seek assistance from a quality Assignment Help USA with a proven track record of delivering well-researched, well-written, plagiarism-free assignments.

    ReplyDelete