Skip to content
nakajima edited this page Sep 12, 2010 · 7 revisions

View the source

The module in callbacks.js lets you specify functions to be called before and after methods are called in a certain object. The callback functions are executed in the scope of the object that is calling the original function, and have access to any arguments passed as well.

Simple Example

When you call $('someLink').update('Something new'), the following messages will be outputted to the console:

  • about to update someLink with Something new
  • just updated someLink with Something new

Here’s the snippet:

var link = $('someLink');

Callbacks.add(link, {
  before: {
    update: function(content) {
      var callerID = this.identify();
      console.info('about to update ' + callerID + ' with ' + content);
    };
  },

  after: {
    update: function(content) {
      var callerID = this.identify();
      console.info('just updated ' + callerID + ' with ' + content);
    };
  }
});

Better example

In Prototype.js’s class implementation, superclasses have a subclasses array that contains exactly what the name would imply. This array let’s see what classes have inherited from a given class. Unfortunately (at least, as far as I can tell), there’s no way to tell to tell when they’re inheriting from it. Using the Callbacks module, we can allow specify behavior for when a class is inherited from:

Callbacks.add(SomeSuperClass.subclasses, {
  before: {
    push: SomeSuperClass.inherited
  }
});

The above code snippet specifies a function to called after a new subclass is pushed into SomeSuperClass.subclasses. It’d be nice to have this hook in Prototype by default, but it’s not tough to add it with callbacks.js.