views:

76

answers:

1

One of the nice things about MooTools, is that it lets you easily assign/fire events to objects, for example:

var playerSingleton = new (new Class({
  Implements: [Events],

  initialize: function() {},

  setVolume: function() { 
    // do some stuff..
    this.fireEvent('volumeChanged')
  }

}));

// Somewhere else...

playerSingleton.addEvent('volumeChanged', function() {
  // do something when volume changes
});

playerSingleton.setVolume(75);
// bam our event fires.

How would something like this be done with jQuery? I know there's .bind and .trigger, but it seems like the only way to do this is to bind/fire events to the window object:

$(window).bind('volumeChanged', fn);

Is there anything better than this, more like the MooTools approach? Thanks!

+1  A: 

jQuery's bind and trigger seem to work on normal objects. Haven't seen the source code to see how it works (if it's part of the public API or not), but it does. See this discussion from last year poking around the same idea.

player is a regular object, with methods to set volume, and add listeners for volume change. an example here.

var player = {
    setVolume: function() {
        $(this).trigger("volumeChanged");
    },

    addVolumeChangeHandler: function(fn) {
        $(this).bind("volumeChanged", fn);
    }
};

// add a listener
player.addVolumeChangeHandler(function() {
    alert("volume has been changed");
});

// change volume (should fire the attached listener)
player.setVolume(); // alerts "volume has been changed"
Anurag
Let me try this.. thanks!
Infinity