About design and nearby

jQuery Namespaced Events for Safer Event Handling

Posted: March 31st, 2015 | Author: | Filed under: Development, Tips and Tricks | Tags: , , , , , , | No Comments »

Probably it’s a well-known feature of jQuery events.. and uncommon at the same time.

It’s easy to add and remove an event handler in jQuery. You could remove a handler because you don’t need to produce any actions on that event anymore or to reduce memory usage, or both. The problem happens in case you’ve attached several handlers to the same event – you are not able to remove just one of them.. without namespacing.

The event.namespace property returns the custom namespace when the event was triggered.

So

  1. $(window).bind('resize', function (){
  2. console.log("doSomething");
  3. });

matches everything and

  1. $(window).bind('resize.myEvents', function (){
  2. console.log("doSomething");
  3. });

binds resize.myEvents only and does not affect other scripts that use the same event.

With .unbind() you do the same exactly:

  1. $(window).unbind('resize.myEvents', function (){
  2. console.log("doSomething");
  3. });

I used it recently while working with resizing jqGrid table. The idea was to bind a resize event, then change the width of grid table and unbind the event. Usage of namespacing was needed to avoid unbinding anything that I didn’t bind myself:

  1. $(window).unbind('resize.myEvents').bind('resize.myEvents', function () {
  2.         var outerwidth = $('#grid').width();
  3.         $('#list').setGridWidth(outerwidth);
  4. });

Check standalone example: Responsive jqGrid: Namespaced Events >>

Share Button

Check Related Posts:


Leave a Reply


  • 3 × = twenty one

Looking for a Freelance UX & UI designer for your project? I’m ready to jump onboard!

Let's discuss your project now