Archive for the 'mootools' Category

Extending DOM Nodes with Mootools

Tuesday, September 26th, 2006

One of the really useful features of JavaScript is the flexibility of its objects. Developers have spent a lot of time looking for ways to emulate the class system of most Object-Oriented Programming languages, which has been a worthwhile pursuit. Mootools itself gives us one of the most elegant solutions to the problem of defining classes in JavaScript.

But one of the unique aspects of JavaScript is the ability to assign arbitrary properties and methods to any object, regardless of how that object was created. This has led to tricks like extending JavaScript’s native Array and String objects. But did you know you can extend DOM nodes as well?

Attaching methods to Elements

The Mootools library takes full advantage of JavaScript’s ability to attach custom methods to DOM node elements. Unfortunately, because of Internet Explorer’s implementation of DOM nodes, these methods can’t be attached to Element prototypes in a cross-browser fashion. But Mootools does let you pass a reference to a DOM node through the $ function to extend that node with the library’s Element methods. This means that once you’ve called $ on an Element, you don’t have to call it again:

var h1 = $('heading');
h1.setHTML('Updated!');
document.getElementById('heading').appendText('...again.');

The third line of code is purely for demonstration purposes. There’s no need to call document.getElementById on the element, but the point is to show that even if you’re not referencing the variable returned by $, the DOM node itself has been extended.

The Element class in Mootools has been turned into a native object, so you can extend it to add to the methods that get copied onto all DOM nodes passed through the $ function, just like the Mootools system of extending objects. This is similar to extending a native JavaScript object, with the exception that it only works on DOM nodes passed through $ after calling Element.extend:

Element.extend({
  alert: function() {
    alert(this.innerHTML);
  },
  log: function() {
    try {
      console.log(this);
    } catch(e) { alert(this.outerHTML);}
  }
});

$('heading').alert();
$('heading').log();

The $ function also adds an extend method to the DOM node passed to it, allowing individual nodes to be extended with custom methods:

var h1 = $('heading');
h1.extend({
  custom: function() {
    // Custom method for only this element
  }
});

Mootools’ new Element class

The $ function in Mootools extends a DOM node with all the methods of Element.prototype. But Element is also a class that can be instantiated. This is useful for extending a reference you already have to a DOM node that may not have an ID:

var link = new Element(document.getElementsByTagName('a')[0]);

// link contains reference to DOM node that has all methods of Element

Where the Element class really shines is as a shortcut for creating new DOM nodes. If you pass a string into Element’s constructor, Mootools will call document.createElement on that string, then pass the created DOM node through the $ function. This is a very handy shortcut, and cool syntactic sugar:

var h1 = new Element('h1');
h1.appendText('Hello World');
h1.injectInside($E('body'));

Or if you’re comfortable with chaining methods:

var h1 = new Element('h1').appendText('Hello World').injectInside($E('body'));

Subclassing the Element class

This leads to a really expressive capability of Mootools: creating new DOM nodes from custom classes. Remember the old JavaScript image rollover days when the way to preload an image was to call var img1 = new Image();? Now you can use similar custom element constructors in your code to give individual element types streamlined constructors and their own unique methods.

Your first attempt at this would probably be along the lines of trying to extend the Mootools Element class. This doesn’t work, because Element is a native Mootools object. Calling Element.extend adds methods to the Element super class instead of copying the Element class to a new class. Luckily the Element constructor shows us the solution to our problem.

Look at the Element.initialize method and you’ll see that it returns an object. I’m used to thinking in terms of PHP, where class constructors can not return anything because the instantiated object is always assigned from the constructor. In a JavaScript object constructor, any object can be returned. That means we can use our custom Element class’s constructor to create our element, extend the element with the methods of the current class, and then return that element. An example will make this clearer:

var Link = new Class({
  initialize: function(options) {
    options = Object.extend({
      href: '#'
    }, options || {});

    var link = new Element('a');
    link.extend(this);

    for (var i in options) {
      link.setAttribute(i, options[i]);
    }

    return link;
  },

  disableClick: function() {
    this.onclick = function(){ this.blur(); return false; };
    return this;
  },

  enableClick: function() {
    this.onclick = Class.empty;
    return this;
  }
});

The magic happens on the line where we call link.extend(this). When a JavaScript object is instantiated via the new operator, a blank object is created from the prototype of that object’s constructor. That means this inside an object constructor refers to the blank object and contains all the methods attached to the prototype of the constructor. So extending the DOM element we just created with this copies all the methods and properties of our prototype into the DOM node.

We’re also using the Link constructor to set up some simple default parameters to help make creating links easier in the future, and giving links created via this class some simple utility functions for disabling click events. The object could be created with the following:

var link = new Link({href: 'http://www.google.com', title: 'The omnipotent one'});
link.appendText('click here').injectInside($E('body'));
link.disableClick();

This would create a new <a> element that has been extended with Mootools’ DOM node extensions, inserted into the document, and with a disabled click event.

Something else useful — sometimes you’ll have DOM nodes already created that you’d like to give the Link methods to. This can be done in one of two ways. The most direct is to call element.extend, passing in Link.prototype. The other method is to instantiate a new Link object but pass in ‘noinit’ as the parameter, which will keep the initialize method from running when creating the object. Each method performs essentially the same thing and is a matter of personal taste:

var link = new Element(document.getElementsByTagName('a')[0]);
link.extend(new Link('noinit'));

// Accomplishes the same thing:
link.extend(Link.prototype);

Go forth and experiment

Hopefully you’ve seen the expressive power that the Mootools way of handling DOM nodes can give you when writing your own code. Go on and experiment with custom DOM node classes and let me know what you find. One word of warning — be careful when using this.parent() inside a custom DOM element method. I haven’t fully tested it yet, and it seems to work in most cases, but one time it did fail in Internet Explorer while I was trying something on an <iframe> element.

Related resources

Useful Utility Functions in mootools

Thursday, September 14th, 2006

The new mootools JavaScript framework has quickly impressed me with its design and usefulness. The library was clearly written to meet real programmers’ needs while working in JavaScript. Just take a look at some of the new utility functions and methods it provides.

Note: This article covers functions and methods found in the Array.js and Function.js modules of mootools.

A cleaner array iterator

Mootools provides a Prototype-inspired each method that every JavaScript array inherits. Its syntax is a bit cleaner because it’s based on the Mozilla Array.prototype.forEach method. The mootools each method allows you to pass in a second parameter as the context in which the function will be called, allowing you to resolve the this keyword. Accomplishing this in the Prototype library involves binding the function passed to each:

var x = {sum: 0};

for (var i = 0, fixtures = []; i < 500; i++) {
  fixtures.push(i);
}

fixtures.each(function(el, i) {
  this.sum+= i
}.bind(x));

// x.sum = 124750

Accomplishing the same thing in mootools is just a small syntax change (the changed line is highlighted):

var x = {sum: 0};

for (var i = 0, fixtures = []; i < 500; i++) {
  fixtures.push(i);
}

fixtures.each(function(el, i) {
  this.sum+= i
}, x);

// x.sum = 124750

The mootools each method takes the object that will resolve to this inside the loop as the second argument.

Why should you care about this minor syntax change? Because calling bind on a function every time through a loop is going to add overhead to your code’s performance. I’ve run the previous code in Firebug with a timer and the results are very telling:

500 elements each with bind: 39ms
500 elements each: 3ms
1000 elements each with bind: 75ms
1000 elements each: 6ms

Not only is the mootools syntax cleaner, but it performs almost 10 times faster than using the bind method. Keep in mind that these examples all use mootools’ each method. If I’d used the Prototype each the code would have run even slower, but that issue has already been well-documented.

Prototype each diversion

The reason Prototype’s each loop runs so slowly is that each iteration of the loop has to run through a try/catch block in order to look for break and continue statements. If you’re using Prototype’s each and you want to break or continue in the loop, you must use the following syntax:

[1,2,3,4,5,6,7,8,9,10].each(function(el) {
  if (el > 7) throw $break;
  if (el == 4) throw $continue;
  alert(el);
});

// Will alert "1", "2", "3", "5", "6", "7"

I’m not here to bash Prototype. It’s a great library. But I think it does need to be pointed out that its each method will run slower than traditional loops because of the design decision to incorporate a workaround for break and continue statements.

What, you’re not using break and continue statements? They can really help you cut down on loop iterations. There is no way to use break or continue in an each loop in mootools, so keep that in mind. You’ll have to use the good old-fashioned for loop for that one.

Running code at time intervals

JavaScript provides the setTimeout and setInterval functions for running code after a delay or at regular intervals. This comes in very handy for animations, but also for other GUI functions, such as delaying hiding a menu after navigating away. The native syntax for this can get a little verbose sometimes, so mootools provides some utility functions as methods of every function. To run code once after a time delay you use the delay method:

(function(){ alert("Sorry I'm late."); }).delay(5000);

This will run the function after a delay of 5 seconds. You can also run code at a regular interval using the periodical method:

var annoy = (function(){ console.log('Are we there yet?'); }).periodical(5000);

The previous code will run until the window unloads unless we clear the interval returned by periodical. Mootools provides a $clear function that will clear any time interval passed to it, whether it was created with delay or periodical:

$clear(annoy);

Just be sure to assign the periodical function to a variable, or else you won’t be able to clear it! Talk about annoying…

The second parameter to delay and periodical is the context object to call the function within, just like the each method. This can come in handy when using methods of mootools’ objects:

var xhr = new Ajax('url', {update: ajaxElement});
var $req = xhr.request.periodical(60000, xhr);

This code will create an Ajax object that calls its request object every minute. You need to pass the Ajax object as the second argument to periodical so the request method will run in the right context.

Cleaner object detection

Sometimes checking the type of a JavaScript object can get confusing. Everything is actually an Object, so running [1,2,3] instanceof Object returns true, even though we were checking against an array. But curisouly, running 'string' instanceof Object returns false! There’s also the typeof function, so things can get rather confusing and frustrating in a hurry when trying to detect object types. Mootools provides a function called $type that will do the proper checks behind the scenes and return a lowercase string type of the element you passed into the function. If the type of object is not matched, $type will return false.

The types returned by $type are:

  • function
  • textnode
  • element
  • array
  • object
  • string
  • number
  • false

Try it out:

$type(function(){});
// Returns 'function'

$type(document.createElement('div'));
// Returns 'element'

$type([]);
// Returns 'array'

$type({});
// Returns 'object'

$type('hello world');
// Returns 'string'

$type(4);
// Returns 'number'

Mootools just continues to amaze me. I’m digging through the source code and running lots of tests to see just how the library works, so stay tuned for more articles about this new library’s features.

Extending Objects and Classes with mootools

Tuesday, September 12th, 2006

I love the moo libraries. Despite my passion and knowledge of the Prototype JavaScript libary, I’ve never used it in a commercial project. I have used moo.fx (and the included prototype.lite) for actual client work and been very satisfied with the results. The moo libraries are very lightweight, organized and clean. They are well thought-out and extendable, and you won’t find any bloatware within.

Now Valerio Proietti has decided to grace us all with his new library, mootools. mootools is like a cross between Prototype and jQuery, with an emphasis on clean, Object-Oriented code and lean, modular design. The library has the most inspired download feature of all libraries — it allows you to pick and choose modules and automatically figures out the dependencies and compresses the code for you.

In this article we’ll take a look at one of the library’s coolest features: extending JavaScript and the library’s functionality.

Extending objects

On the surface, extending objects in mootools works just like Prototype. There is an Object.extend function that takes two arguments: destination and source.

var test = {hello: 'world'};
Object.extend(test, {animal: 'sloth'});

// test now contains "{hello: 'world', animal: 'sloth'}"

At this point mootools diverges from Prototype and adds some nice functionality to help you extend the libary and JavaScript itself.

Class inheritance

mootools implements a class inheritance scheme that is inspired by Dean Edwards’ wonderful Base class. Creating a class is similar to Prototype, but now you don’t ever have to think about the prototype object when you define the class:

var Shape = new Class({
  initialize: function(width, height) {
    this.width = width;
    this.height = height;
  },
  draw: function() {
    console.log('starting to draw...');
  }
});

Now we’ll probably never use the Shape class because it’s abstract, so let’s see how mootools lets us extend the class:

var Square = Shape.extend({
  draw: function() {
    this.parent();
    console.log('drawing square');
  }
});

Some of you may be wondering where the extend() method on Shape came from. You can breathe a sigh of relief, because it’s not coming from Object.prototype (whew!). Any class created with new Class() gets an extend method. When you use the extend method to define a child class, the parent class remains untouched. The child class inherits all of its parents’ properties and methods. Each of the child’s methods also has access to the parent’s method of the same name, accessed by calling this.parent() within a method.

To see this in action, let’s instantiate a new Square object:

var square = new Square(150, 150);
square.draw();

// Logs "starting to draw...", then "drawing square" to the console

Finally, an easy way to define classes and inheritance schemes in JavaScript!

Multiple inheritance with Class.implement()

mootools supports multiple inheritance in a Ruby mixin style with the Class.implement() method. Using the implement method of an existing class, that class can inherit methods and properties from another class or object. Unlike Class.extend(), the implement method is called on the class you are modifying, not on the object being copied. This method can be used to support multiple inheritance:

var UsefulGlobalObject = {
  inspect: function() {
    var results = [];
    for (var i in this) {
      results.push(i + ': ' + this[i]);
    }
    return results.join(",n");
  }
};

var Circle = Shape.extend({
  draw: function() {
    this.parent();
    console.log('drawing circle');
  }
});

Circle.implement(UsefulGlobalObject);

Let’s assume UsefulGlobalObject really is a useful global object. Passing this object to Circle.implement() copies all properites of the object to Circle’s prototype, so any circle object will now have the method inspect(). If we were copying from a parent class instead of an object, the syntax would use the new keyword:

Shape.ThreeDimensional = new Class({
  rotate: function(degrees, plane) {
    console.log('rotating by ' + degrees + ' on the ' + plane + ' plane');
  }
});

var Sphere = Shape.extend({
  draw: function() {
    this.parent();
    console.log('drawing sphere');
  }
});

Sphere.implement(new Shape.ThreeDimensional);

Sphere has inherited from both the Shape class and the Shape.ThreeDimensional class.

Extending library classes and native objects

Another use for the implement() method is for modifying a library class in a different code module, or even dynamically adding to a class at runtime. This is similar to Ruby, where you can reopen a class definition at any time to add new methods. We can use the implement() method to add or overwrite any method in a mootools class in our own code so that we don’t have to modify the library itself:

Ajax.implement({
  // add a new method
  newMethod: function() {
    // new method code
  },

  // overwrite an existing method
  request: function() {
    // overwrite the original request method
  }
});

This code will add a new method newMethod and overwrite the request method for the Ajax object.

One last feature of the mootools library is the concept of Native Objects. String, Function and Array have been turned into mootools native objects, which essentially means their extend() method is an alias for the implement() method. Calling extend() on these objects adds properties and methods to them just like Class.implement() does. It makes the syntax for extending a native object even sweeter:

Array.extend({
  map: function(fn) {
    for (var i = 0, a = []; i < this.length; i++) {
      a[i] = fn(this[i]);
    }
    return a;
  }
});

Any method you extend a JavaScript native object (String, Function, Array) with will have the new methods attached, even if it was created before the call to extend(). Note that the Number object is not a native object in mootools, but you can easily change that by calling Object.Native():

new Object.Native(Number);

Number.extend({
  isOdd: function() {
    return !!(this % 2);
  }
});

mootools also provides the Element and Elements classes as native objects, so they can easily be extended just as JavaScript native objects:

Element.extend({
  visible: function() {
    return this.style.display != 'none';
  },

  toggle: function() {
    this[this.visible() ? 'hide' : 'show']();
    return this;
  },

  hide: function() {
    this.style.display = 'none';
    return this;
  },

  show: function() {
    this.style.display = '';
    return this;
  }
});

The Element class in mootools contains all the methods that get bound onto any DOM node passed through the $() function. Note that if you call Element.extend(), any methods or properties you add to the Element class won’t automatically be added to any elements that have already been run through the $() function. We’ll cover extending DOM nodes in an upcoming post.

Plugin friendly

The mootools library is brand new, but it has a solid codebase that stands on the shoulders of giants like Prototype and Dean Edwards. It provides a lot of great features right out of the box, but it’s also been written to make class inheritance and object extension very simple. This encourages traditional use of class inheritance schemes, as well as adding your own extensions and plugins to the library on an as-needed basis, without having to modify the original source code.