Extending MooTools is Easy!

I’d never attempted to extend MooTools before, but while trying to make its api a little more similar to jQuery, I found out it’s rather simple. I like how jQuery has a function for each event like $(el).click(fn). A lot prettier than $(el).addEvent('click', fn). After digging around in MooTools a bit, I figured out how to do that in 10 lines:

(function(events){
    var methods = {};
    for (var event in events) {
        (function(ev){
            methods[ev] = function(fn){
                return (fn) ? this.addEvent(ev, fn) : this.fireEvent(ev);
            }
        })(event);
    }
    Native.implement([Element, Window, Document], methods);
})(Element.NativeEvents);

I can also use $(el).click() to trigger the click event just like jQuery.

Next, let’s say I like $(document).ready(fn) better than window.addEvent(’domready’, fn). Just do the following:

Document.implement({
    ready: function(fn) {
        window.addEvent('domready', fn);
    }
});

And finally, while this is purely aesthetics, I like $(el).is(selector) better than $(el).match(selector). Internally MooTools uses alias() to assign the same function multiple names so I can do that too like this:

Element.alias('match', 'is');

With these changes I can now use this code with MooTools:

document.ready(function(){
    $('myLink').click(function(e){
        if (e) e.preventDefault();
        alert($(this).is('a'));
    }).click();
});

And combined with some simple wrappers for jQuery, this is also valid jQuery code.

6 Responses to “Extending MooTools is Easy!”

  1. Lim Chee Aun

    Nice code! I’m actually working on extending Mootools to have (almost if not) all jQuery-like syntax. When I was working on .click(), please do note that it conflicts with the native prototype ‘click’ method of input elements, eg: input.click(). This affects .blur() and .focus() as well.

  2. Chris

    Hmm, you’re right. I haven’t done too much testing yet. Did you come up with a work-around? I’d like to see what you’ve done.

  3. Lim Chee Aun

    I couldn’t find much of a work-around though. My work is over here: http://mooj.googlecode.com/

  4. Chris

    @Lim Chee Aun: Wow, that’s pretty nice. If only all libraries could be extended so easily! My eventual goal is to create a consistent API across as many libraries as I can.

  5. Lim Chee Aun

    Well, consistent API is kinda possible, but the problem is the syntax though. jQuery style or Mootools? :)

  6. Chris

    I think jQuery style would be easiest, namespacing everything in a single object, but I prefer Mootools’s approach to extending native objects. It creates a much nicer experience.

    I was attempting to get the sippet of code above working in Prototype as well, but it doesn’t have a fire event function and I didn’t get around to making one yet.

Leave a Reply