Fun With Mootools Part 1: The Class toElement method

T

he MooTools ( My Object Orientated Tools ) JavaScript framework is a pretty sweet piece of software. It's goal is to make developing with JavaScript easier. It provides large set of tools for building complex JavaScript applications. There are a lot of hidden goodies tucked away in the framework that kick off one of those "AHa!" moments. One of those goodies is the toElement method on classes. One of those goodies is the toElement method on classes.

The Class' method, toElement, works in tandem with the MooTools document.id ( $ ) method. In most cases, Classes center around a DOM element for some reason or another. As a convenience, the document.id ( $ ) will call the toElement method when it is passed an instance of a MooTools Class.

var MyClass = new Class({  
    /**
     * The Constructor
     * @constructor
     */
    initialize: function( el ){
        this.element = document.id( el );
    }

    /**
     * Kills the internal elemnt
     * @method die 
     */
    ,die: function(){
        this.element.destroy();
    }

    /**
     * Method that calls some function
     * @method someFn 
     * @param args {Things}
     */
    ,someFn: function( args ){
        this.doSomething( args );
    }

    /**
     * The method that does something
     * @method doSomething
     * @return {Number}
     */
    ,doSomething: function(){
        return args[0] + 4;
    }

    /**
     * here is the magic
     * @method toElement
     * @return {HTMLElement}
     */
    ,toElement: function(){
        return this.element;
    }}
);
var myCls = new MyClass( "someElementID" );

document.id( myCls ).fade('out') // The element will fade out!  

It is a simple function that, in it self, doesn't do much. However, what it does do is, allow a bit of abstraction. Once the class has been created, you don't need to hard-code the CSS Selector, or dig through property accessors on the class when you want to work with the DOM element. You can just pass the entire class instance through document.id and start working. Give it a try, it helps keep your code cleaner and makes life quite a bit easier

dom oop mootools class javascript