Extending MooTools is Easy!
October 13th, 2008 in web development | 6 Comments
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.

Hi, I'm Chris, a passionate freelance web developer. My languages of choice are PHP and JavaScript, and that's what you'll mostly find in my blog. You'll also find updates about 