Default Event Handlers in MooTools 1.2 Classes

I recently started converting some UI components I created in MooTools 1.1 into 1.2 versions to use on a new project. For a point release, I’m surprised how different a lot of the MooTools syntax is in the latest version. One thing that took a bit of getting used to was how inheritance has changed, and the knock on effects when using Options and Effects in my classes.

In the MooTools 1.1 version I had a base class, ‘Widget’ which I would extend as below:

var DialogBox = Widget.extend({ … });

Widget implements both Options and Events which allowed me to create a set of events the widget can fire, handlers for which can be added through options, as such:

var DialogBox = Widget.extend({
  options : {
    onCancel : this.close.bind(this)
  }
  ...
});

Because extend is a method of Widget, its ‘this’ is the object itself and, provided there is a close method, the event handler for ‘cancel’ is set up.

MooTools 1.2 introduces a new syntax for extending objects:

var DialogBox = new Class({
  Extends : Widget,

  options : {
    onCancel : this.close.bind(this)
  },
  ...
});

Now, the ‘this’ is actually the window object so the cancel event is actually handled by the window.close method - not quite the functionality intended!

After digging around in the MooTools code, in particular the Request.HTML class, I found what appears to be the only way to default events in options. By setting the option before calling setOptions (if it isn’t already set), the event handler is correctly assigned:

var DialogBox = new Class({
  Extends : Widget,

  options : {
    ...
  },

  initialize: function(options) {
    options.onCancel = options.onCancel || this.close.bind(this);
    this.setOptions(options);
  },
  ...
});

The binding is now done on instantiation so the correct close method is assigned as the cancel event handler.

Tags: , , , ,

Leave a Comment