jQuery On and Off Namespacing
Quite a while ago, I wrote an article about jQuery .on() and off() - an improved way of attaching events in jQuery - and still the best way to attach events to DOM elements in jQuery.
Being able to apply and remove events with on()
and off()
is great, but
sometimes there is a requirement to either trigger or remove a subset of
events that have been added to an element. For example:
$(".item").on("click", doThisCoolThing);
$(".item").on("click", doThisOtherCoolThing);
$(".item").trigger("click"); // both functions are triggered
$(".item").off("click"); // both functions are removed.
Using event namespacing we can assign names to event handlers when we create
them, and then use them later on to target specific functionality when we call trigger()
or off()
. The name you choose for your event namespace should be relevant for the functionality you are calling. For example:
$(".item").on("click.navigate", doThisCoolThing);
$(".item").on("click.notify", doThisOtherCoolThing);
// only the function assigned to the namespace navigate would be triggered.
$(".item").trigger("click.navigate");
// only the function assigned to the namespace notify would be removed.
$(".item").off("click.notify");
It's also possible to use multiple namespaces, like so:
$('.item').on('click.navigate.notify', doThisCoolThing);
// trigger the click event
$('.item').trigger('click.navigate');
function.
// remove the click event.
$('.item').off('click.notify');
Namespacing events in jQuery has been available for some time and isn't
limited to just on()
and off()
. It also works with .bind()
and
.unbind()
too.
More Blog Posts
Observability with Slack Workflows
I recently needed to keep an eye on a third party's rate limit during a product launch, and Slack Workflows seemed like a nice solution to alert me to issues. Let's take a look at how it worked.
Peacetime vs Wartime
Your monolith is buckling under heavy traffic growth. The quick fix is to beef up the server through vertical scaling and buy yourself six months. The right fix is a four month microservices migration that will either save the company or kill it if you miss the deadline. Meanwhile your $2m client is demanding new features or they'll go elsewhere.
From Sprawl to Structure
The business is growing, and your engineering team is too. Great news - until the sprawl sets in. How can your teams and processes scale with consistency and maturity?
Ship Fast, Scale Clean - Building MVPs That Last
Your founder comes to you with the classic Minimum Viable Product (MVP) dilemma. We need to build quickly for speed to market, but make it maintainable so it can scale as we grow.