{"id":156362,"date":"2013-11-18T06:11:02","date_gmt":"2013-11-18T13:11:02","guid":{"rendered":"http:\/\/css-tricks.com\/?p=156362"},"modified":"2013-11-22T19:04:26","modified_gmt":"2013-11-23T02:04:26","slug":"namespaced-events-jquery","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/namespaced-events-jquery\/","title":{"rendered":"Namespaced Events in jQuery"},"content":{"rendered":"

It’s really easy to add an event listener in jQuery. It’s equally easy to remove an event listener. You might want to remove a listener because you don’t care to perform any actions on that event anymore, to reduce memory usage, or both. But let’s say you’ve attached several listeners to the same event. How do you remove just one of them? Namespacing can help.<\/p>\n

<\/p>\n

Let’s look at code.<\/p>\n

$(\"#element\")\r\n  .on(\"click\", doSomething)\r\n  .on(\"click\", doSomethingElse);<\/code><\/pre>\n

Both<\/strong> doSomething<\/code> and doSomethingElse<\/code> will fire when that element we’ve selected is clicked. That’s good. It’s one advantage of using jQuery to bind events rather than super old school onclick<\/code> which would overwrite previously declared event handlers.<\/p>\n

Now let’s say you want to remove the first of those event listeners, the one that fires doSomething<\/code>. How do you do that?<\/p>\n

$(\"#element\").off(\"click\");<\/code><\/pre>\n

Careful there, that will unbind both of those handlers which is not what we want. <\/p>\n

Luckily jQuery will take the same second parameter with .off()<\/code> as it does with .on()<\/code>.<\/p>\n

$(\"#element\").off(\"click\", doSomething);<\/code><\/pre>\n

That’s great if you have a reference to an actual function that you can pass in as that parameter. But what if you don’t have that reference? Either because you don’t know what it is or you used an anonymous function as the handler, like this:<\/p>\n

$(\"#element\")\r\n  .on(\"click\", function() { \r\n     console.log(\"doSomething\");\r\n   });<\/code><\/pre>\n

How do you unbind that one in a safe way that won’t accidentally unbind other click handlers? Namespaced events<\/a>!<\/p>\n

Instead of just click<\/code> as the name of the event, you can use click.namespace<\/code>.<\/p>\n

$(\"#element\")\r\n  .on(\"click.myNamespace\", function() { \r\n     console.log(\"doSomething\");\r\n   });<\/code><\/pre>\n

Now you can use .off()<\/code> with that exact event name to unbind just<\/em> it.<\/p>\n

$(\"#element\").off(\"click.myNamespace\");<\/code><\/pre>\n

Just one of those cool useful things in jQuery. Even with modern event binding using addEventListener<\/code> and removeEventListener<\/code> this would be a bit tricky (I think).<\/p>\n

I used it recently in that bookmarklet I made to test line length<\/a>. I essentially wanted to bind a mouseenter<\/code> event on every single element on the page (using delegation) and then when one is clicked, unbind both those events. But I wanted to be careful not to unbind anything that I didn’t bind myself. Hence, namespacing!<\/p>\n

Want to learn more about jQuery? I have a complete course available<\/a>.<\/div>\n","protected":false},"excerpt":{"rendered":"

It’s really easy to add an event listener in jQuery. It’s equally easy to remove an event listener. You might want to remove a listener because you don’t care to perform any actions on that event anymore, to reduce memory usage, or both. But let’s say you’ve attached several listeners to the same event. How […]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"sig_custom_text":"","sig_image_type":"featured-image","sig_custom_image":0,"sig_is_disabled":false,"inline_featured_image":false,"c2c_always_allow_admin_comments":false,"footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":[]},"categories":[4],"tags":[265],"jetpack_publicize_connections":[],"acf":[],"jetpack_featured_media_url":"","jetpack-related-posts":[{"id":169949,"url":"https:\/\/css-tricks.com\/jquery-coffeescript\/","url_meta":{"origin":156362,"position":0},"title":"jQuery with CoffeeScript","date":"May 13, 2014","format":false,"excerpt":"I don't always write CoffeeScript, but when I do, I'm probably using jQuery too; I always forget the syntax for stuff. So I'm going to write it all down here so I can reference it until I memorize it. Note that the compiled example doesn't include the automatic closure around\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":330593,"url":"https:\/\/css-tricks.com\/lets-create-a-lightweight-native-event-bus-in-javascript\/","url_meta":{"origin":156362,"position":1},"title":"Let\u2019s Create a Lightweight Native Event Bus in JavaScript","date":"December 11, 2020","format":false,"excerpt":"An event bus is a design pattern (and while we\u2019ll be talking about JavaScript here, it\u2019s a design pattern in any language) that can be used to simplify communications between different components. It can also be thought of as publish\/subscribe or pubsub. The idea is that components can listen to\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2020\/12\/event-bus-js-vw.jpg?fit=1200%2C600&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":286888,"url":"https:\/\/css-tricks.com\/the-thinking-behind-simplifying-event-handlers\/","url_meta":{"origin":156362,"position":2},"title":"The Thinking Behind Simplifying Event Handlers","date":"May 9, 2019","format":false,"excerpt":"Events are used to respond when a user clicks somewhere, focuses on a link with their keyboard, and changes the text in a form. When I first started learning JavaScript, I wrote complicated event listeners. More recently, I've learned how to reduce both the amount of code I write and\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2019\/05\/event-handlers.png?fit=1200%2C600&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":332292,"url":"https:\/\/css-tricks.com\/3-approaches-to-integrate-react-with-custom-elements\/","url_meta":{"origin":156362,"position":3},"title":"3 Approaches to Integrate React with Custom Elements","date":"January 15, 2021","format":false,"excerpt":"In my role as a web developer who sits at the intersection of design and code, I am drawn to Web Components because of their portability. It makes sense: custom elements are fully-functional HTML elements that work in all modern browsers, and the shadow DOM encapsulates the right styles with\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2018\/09\/react-recompose-hand.png?fit=1200%2C600&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]},{"id":19321,"url":"https:\/\/css-tricks.com\/treehouse-ad\/","url_meta":{"origin":156362,"position":4},"title":"The Making of the Interactive Treehouse Ad","date":"December 30, 2012","format":false,"excerpt":"We go through the planning and creation of the interactive Treehouse ad on this site.","rel":"","context":"In "Article"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":306810,"url":"https:\/\/css-tricks.com\/alpine-js-the-javascript-framework-thats-used-like-jquery-written-like-vue-and-inspired-by-tailwindcss\/","url_meta":{"origin":156362,"position":5},"title":"Alpine.js: The JavaScript Framework That’s Used Like jQuery, Written Like Vue, and Inspired by TailwindCSS","date":"April 29, 2020","format":false,"excerpt":"We have big JavaScript frameworks that tons of people already use and like, including React, Vue, Angular, and Svelte. Do we need another JavaScript library? Let\u2019s take a look at Alpine.js and you can decide for yourself. Alpine.js is for developers who aren't looking to build a single page application\u2026","rel":"","context":"In "Article"","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/css-tricks.com\/wp-content\/uploads\/2020\/04\/alpinejs.png?fit=1200%2C600&ssl=1&resize=350%2C200","width":350,"height":200},"classes":[]}],"featured_media_src_url":null,"_links":{"self":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/156362"}],"collection":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/comments?post=156362"}],"version-history":[{"count":3,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/156362\/revisions"}],"predecessor-version":[{"id":156402,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/posts\/156362\/revisions\/156402"}],"wp:attachment":[{"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/media?parent=156362"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/categories?post=156362"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/css-tricks.com\/wp-json\/wp\/v2\/tags?post=156362"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}