jQuery style events

jQuery events are cool. But what if you want to trigger some events but not extend all your JavaScript objects to jQuery ones? If you are drawing thousands and thousands of these objects to screen you probably don’t want to worry about the overhead of making them jQuery objects.

Here’s how you can write your own simple jQuery style events:

function Meteor() {
  var eventCallbacks = {
    'destroy': alert('destroyed')
  };
 
  var destroyed = false;
 
  var self = {
    bind: function(event, callback) {
      eventCallbacks[event] = callback;
    },
    destroy: function() {
      if (!destroyed) {
        destroyed = true;
        self.trigger('destroy');
      }
    },
    explode: function() {
      // Kaboom
    },
    trigger: function(event) {
      eventCallbacks[event](self);
    },        
  };
  return self;
}

Here’s how you use it

var meteor = Meteor();
meteor.bind('destroy', function() { 
  meteor.explode();
});
 
...
 
meteor.destroy();