Listening for Events with jQuery

Several months ago I learned about event binding using ExtJS or Sencha touch. What you may or may not know is that you can achieve the same thing with jQuery using custom even binding.

In case you do not know about Sencha nor do you not work with Sencha, let me explain event binding. Event binding can be used to loosely couple actions so they never break. Essentially, you broadcast to your entire application “Hey! I have something to say! Does anybody want to hear it?” Your modules can either say “Hey, I’d like to hear what you have to say” or else, they can just ignore it. Either way, nothing breaks. You can even have several modules respond to the same event in different ways.

Make sure that you are using an up to date version of the jQuery library. I remember having some trouble with this in the past.

To create a custom event with jQuery, you can use the “trigger” function like this:

   $(document).trigger(‘my-custom-event’, [‘hi!  I am a custom variable!’]);

You can actually bind a custom event to any DOM element, but for the sake of making it available to your entire application, the document object is usually a pretty safe choice. As you can see, we are also passing a variable.

Now you just need to have a listener at any place in your code that is executed before the trigger event, like this:

   $(document).bind(‘my-custom-event’, function(v) {
      alert(v);
   });

So your code ends up looking something like this:

   $(document).bind(‘my-custom-event’, function(v1, v2) {
      alert(v1);
   });

   $(document).bind(‘my-custom-event’, function(v1, v2) {
      alert(‘firing ‘ + v2);
   });

   $(document).trigger(‘my-custom-event’,  [
      ‘Hi!  I am a custom variable!’,
      ‘Hi! I’m a different custom variable!’
    ]);

You should now see two separate alerts fired from the same trigger. Now all you have to do is bind custom events to your individual modules and they will never touch again. Empowering isn’t it.

Advertisements

I am a technologist with a strong background in software engineering. I have many interests. My current distractions are 70s-80s-90s music [it's a very eclectic collection], ontology, information architecture, mobile device technology, medical bioinformatics, artificial intelligence, and nanorobotics.

Posted in Uncategorized

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: