Today I Learned

hashrocket A Hashrocket project

Best practice for event binding in JavaScript

When binding an event to a DOM element you often need a way to update your event in runtime. This presents a challenge because setting the new event will not override the existing one but instead create an additional event. In that case you need to namespace (jQuery terminology) your event which will allow you to replace it.

Problem:

$(window).on('scroll', function () { console.log('A') });

// Scroll output: 
// => A
// => A

$(window).on('scroll', function () { console.log('B') });

// Scroll output: 
// => A
// => B
// => A
// => B

Solution:

$(window).off('scroll.myPlugin').on('scroll.myPlugin', function () { console.log('A') });
$(window).off('scroll.myPlugin').on('scroll.myPlugin', function () { console.log('B') });

// Scroll output: 
// => B
// => B

Vanilla JS - when using the addEventListener use named functions (instead of anonymous..). It may be a good idea to keep an array of your event handlers in your object tree.

Solution:

var scrollHandler = function() { console.log('A') };
var scrollHandler2 = function() { console.log('B') };
window.addEventListener('scroll', scrollHandler);
window.removeEventListener('scroll', scrollHandler);
window.addEventListener('scroll', scrollHandler2);

// Scroll output: 
// => B
// => B

This is especially important when writing your own libraries to avoid collisions with user events.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.