JavaScript and/or jQuery custom events

JavaScript and/or jQuery custom events


I am developing a Controller for an MVC style custom object and I'd like to connect some sort of event handling mechanism.

It's not important what the controller is, but let's say I have a couple of events such as "happening" and "happened". Something like this:

  1. $(".happeningCtrl").happening(function(args) { /* something is about to happen */ });
  2. $(".happeningCtrl").happened(function(args) { /* something just happened */ });
Along these lines, with them being raised something like this:

  1. $(".happeningCtrl").happening();
  2. $(".happeningCtrl").happened();

Good so far?

Event driven programming is not new to me, but how JavaScript and/or jQuery approach it is somewhat new. Much of the background discussion I am finding revolves around DOM this and DOM that. However, in this case, we are talking about a custom controller, for which I would like to extend (?) a custom event or three.

Thus far I have approached it as a kind of poor man's event handler with ad-hoc JavaScript arrays of $.isFunction(...) verified handlers. Not the safest way to accept event handlers, I agree, but it will "work".

However, if there is a better way of accomplishing this using jQuery, for instance, I'd like to pursue that instead, provided the overhead isn't too steep for assuming that as a dependency.

Don't know if any of this makes sense. Can someone offer any guidance or enlighten me as to perhaps a decent tutorial around this topic?