Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 56 ยท Events

Custom Events and Pub/Sub

Create your own jQuery events with .trigger(), pass extra parameters, namespace them, and build a tiny pub/sub event bus with $({}) to decouple components.

Built-in events describe things the browser knows about: clicks, keys, resizes. But your application has its own moments worth announcing: "the cart changed", "the user signed in", "the list finished loading". With custom events you can name those moments yourself, let any part of the page listen for them, and keep the parts from knowing about each other.

You need to be comfortable with .on() and .trigger() from the previous lessons. Everything here works because jQuery treats any string as an event name.

Why custom events

Announce A component says what happened.
Listen Other components decide how to react.
Decouple Neither side needs the other's code.
1 / 2

Triggering and listening

There is nothing special to register. Pick a name, attach a handler for it and call .trigger() with the same name.

JavaScript
$("#panel").on("opened", function () {
  console.log("The panel opened.");
});

$("#panel").trigger("opened");

Event names are just strings. A common habit is to use lowercase words, sometimes with a colon prefix that describes the area: cart:changed, user:login. Avoid names that match built-in events (click, change) unless you mean them.

When you trigger a custom event on a DOM element, it bubbles like a real one, so an ancestor or a delegated handler can listen:

JavaScript
$("#app").on("item:selected", ".item", function (event) {
  console.log("An item was selected:", this.id);
});
$("#item-3").trigger("item:selected");

Passing extra parameters

.trigger() takes a second argument with values to hand to the handlers. They arrive after the event object. Use an array to pass several values.

JavaScript
$("#cart").on("cart:changed", function (event, count, total) {
  console.log(count + " items, total " + total);
});

$("#cart").trigger("cart:changed", [3, 59.5]);

If you pass a single non-array value, such as an object, it arrives as the first extra parameter. A string like "abc" also works, but remember that an array is always unpacked into separate arguments, so wrap an array you want delivered whole in another array: [[1, 2, 3]].

A component announcing changes

The buttons know nothing about the badge or the log. You can add a third listener (say, saving to a server) without touching the code that triggers the event.

Namespacing custom events

Namespaces work exactly like they do for built-in events. They let a component clean up only what it added, and they let you trigger just the handlers from one namespace.

JavaScript
$(document).on("cart:changed.header", updateHeaderBadge);
$(document).on("cart:changed.checkout", updateCheckoutButton);

$(document).trigger("cart:changed.header"); // runs only the .header handlers
$(document).off(".checkout");               // removes the checkout component's handlers

Triggering "cart:changed" with no namespace runs every handler for that event, whatever its namespace.

Building a tiny event bus

DOM elements are not the only objects jQuery can attach events to. Wrap any plain object, even an empty one, and it gains .on(), .off() and .trigger(). That gives you a pub/sub (publish and subscribe) channel that has nothing to do with the page layout.

flowchart LR
  P1["Search box (publisher)"] -->|"publish topic"| B(("bus = $({})"))
  P2["Cart (publisher)"] -->|"publish topic"| B
  B -->|"deliver"| S1["Results list (subscriber)"]
  B -->|"deliver"| S2["Header badge (subscriber)"]
  B -->|"deliver"| S3["Analytics (subscriber)"]

Publishers and subscribers only know the bus and the topic name, never each other.

A small wrapper turns the three jQuery methods into a friendlier API and hides the event object that subscribers rarely need.

JavaScript
var bus = (function () {
  var $o = $({});
  return {
    subscribe: function (topic, fn) { $o.on(topic, fn); },
    unsubscribe: function (topic, fn) { $o.off(topic, fn); },
    publish: function (topic, data) { $o.trigger(topic, [data]); }
  };
})();
A pub/sub bus with three independent widgets

Change the theme and all three cards react. The picker never refers to any of them. Notice that the demo's "unsubscribe" is deliberately blunt: unsubscribe removes every handler for that topic. A real bus would use namespaces or keep the function reference to remove one subscriber at a time.

When to use which

Custom events on DOM elements are best when the event belongs to a piece of the page and ancestors should be able to hear it by bubbling, like a widget announcing opened. A bus on $({}) fits application-level news that is not tied to one element, like authentication or cart changes.

Keep two cautions in mind. Because the connection is by name only, a typo in a topic silently does nothing, so keep topic names in one place. And every subscription keeps its function alive: components that disappear should unsubscribe, which is why namespaced handlers are worth the habit. The best practices lesson returns to cleanup and leaks.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you send two values to a custom event's handler with .trigger()?

    Extra parameters go in an array as the second argument. The handler receives them after the event object: function (event, a, b).
  2. 2. What does $({}) give you in a pub/sub bus?

    jQuery can wrap any object. Events on it do not touch the DOM, so it works as a private message channel.
  3. 3. A custom event is triggered on #item-3 and a handler is bound on its ancestor #app. Does #app's handler run?

    jQuery bubbles triggered events up the DOM tree, so ancestors and delegated handlers can listen.
  4. 4. Why namespace custom event handlers such as cart:changed.header?

    Namespaces make cleanup precise: .off(".header") removes the header component's handlers without affecting anyone else.

Summary

  • Any string is a valid event name; .on() listens and .trigger() fires it.
  • Extra parameters travel in an array and arrive after the event object.
  • Custom events on DOM elements bubble, so delegation works for them too.
  • Namespaces such as cart:changed.header support targeted triggering and cleanup.
  • Wrapping a plain object with $({}) gives you a DOM-free pub/sub bus.
  • Decoupling is the benefit; remember to unsubscribe when components go away.

Events done. Next, start animating the page with Showing and Hiding.