playing with jQuery custom events, good tip from @ajpiano

21 Mar

I’m rewriting WebWait, which includes major refactoring to use a pubsub model, hence jQuery custom events. Best summary of custom events is at :


If you are the “just the facts” type of person, here is the 20 second overview. You can trigger custom events on any DOM object of your choosing using jQuery. Just trigger it using the following code:


You can subscribe to that event using either bind or live functions in jQuery:

1.$("#myelement").bind('fuelified',function(e){ ... });

The element the trigger has been called on, is available to listener’s callback function as the variable this.


But one odd thing about all these intros-to-custom-events is there’s always an element in these examples. Fine for mouse clicks and the like, but the main reason to use custom events, I would have thought, is to add a layer of logic around semantic events, things detached from UI concepts. So in WebWait, it’s things like “trialUpdate” and “trialDelete”. WebWait is a humble single-page app, so why would I want to namespace events? And even if I was namespacing events, why would I want to make the namespace a CSS selector, given that they are semantic (non-UI) in nature?

I tried using $().bind() and $.trigger(), but no luck (and prior to that, I accidentally used $.bind() and $.trigger(), which don’t actually exist). So I jumped onto #jQuery API and @ajpiano immediately informed me you can use $(document).bind() and $(document).trigger(). Problem solved. Of course, I could have used any old element on the page, but (a) doing so would have tied potentially reusable stuff to my application; (b) it’s a cleaner expression of my intent. The less gratuitous details, the better.


2 Responses to “playing with jQuery custom events, good tip from @ajpiano”

  1. matthewaaron September 15, 2010 at 3:45 am #

    I have found <a href="">custom jquery events</a> extremely useful!

  2. Anonymous November 23, 2011 at 4:18 pm #

    In retrospect, this is an antipattern because you shouldn’t be using the DOM to handle generic events…use a custom library (these days, something like Backbone.js or even a very simple pubsub like

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: