Articles in the ‘All’ Category

Dojo and MooTools

Written By Aaron Newton, on Thursday, April 1st 2010, 11:02am

Over the past several months we here at MooTools have been contemplating how much of what we do is duplicated effort. When we started this whole project years ago it was because we wanted to do things our own way, but as MooTools and JavaScript in general have progressed, we find ourselves facing the tedium of all the low lying code that has to be written to get Browsers to play nice, not to mention the richer things like our inheritance system and other utilities like effects, DomReady, etc. etc.

At FOSDEM we ended up hanging out with the Dojo crew. We like them; they are always doing interesting things and their framework is one that we’ve always looked at and said to ourselves, “If we ever needed feature X we’d probably just port it from them.” Anyway, at FOSDEM a group of their developers and ours got together and started brainstorming about closer ways to work together. Since then the discussion has gotten closer and closer to where we are now.

MooJo

Starting today the Dojo and MooTools projects will begin merging and joining forces. Part of this is to share resources - more hands coding makes more code, right? But part of it is, well, we’ll be frank, we’re kind of tired of reinventing the wheel. We love the solutions in MooTools, but at the end of the day, the API is all that matters. It doesn’t matter how you detect that the DOM is ready, so long as when it is your code runs. The same could be said for selector engines, XMLHttpRequest, and a whole host of other things. What this means in practical terms is that we just don’t have to do as much work and, to be frank, after 4 years of working on MooTools, we’re happy to cede some of the more tedious tasks to Dojo. Sure, their architecture isn’t quite the same (or maybe even as good) as ours, but it works. This will free our development team’s time to work on their own projects and maybe start getting paid for it, which brings us to the second point.

Making MooJo Profitable

For the past four years we’ve been writing code and releasing it for free. In our talks with the Dojo team we all agreed that all this free time donated to anyone who happened to want our work just wasn’t quite worth the hassle. Don’t get us wrong, writing the code is fun, but it’s all the other stuff. The bug reports, the hand-holding in the forums and on IRC, the constant demand to “compete” with other frameworks (whatever that means). It just sucks the pleasure right out of it. We find ourselves burning nights and weekends to write code for strangers to use and it gets old.

Going forward, the code base will continue to be free, but access to the documentation will require a small “donation” (we’ll probably set a really small minimum, like, say $.25) - frankly, the documentation has gotten too good to be free (we contemplated printing it and just selling it as a book, but micropayments is much more “Web 2.0”). Filing bugs will still be free of course. But we’re working on a system that lets our users put money towards the bugs they care about the most. The bug with the most money donated gets our time and gets in the next release. We think this will cut down on both the number of bugs we get but also help manage expectations. If you have a bug that you think is important, you either need a lot of people to agree with you (which they will if the bug is really broad) or you need to pay a lot (in which case it’s like you’re hiring us as freelancers).

What will we do with the money raised? We’ll probably start sponsoring more meet-ups and sending more people to conferences, but we’ll also be able to compensate the developers who bring you all this great stuff. Certainly no one can argue with that.

Compatiblity

As we begin merging functionality we’ll likely retire large portions of both frameworks. MooTools has a great effects library while Dojo has a lot of solid widgets. MooTools ART will likely get shelved in favor of dojo.gfx, Dojo will likely drop it’s effects libraries in favor of MooTools’ effects which are really nice, much of MooTools More will either be retired (in favor of existing Dojo widgets) or turned into Dojo widgets themselves, etc.

For backwards compatibility we’ll be implementing the “donation” system as well. For the portions of the MooTools and Dojo cores that are deprecated we’ll allow the users to prioritize which parts we offer compatibility for. Same goes for effects, plugins, etc. We hope this new model will encourage businesses that use our awesome frameworks to recognize the value we bring and to compensate us for our time.

If you have any questions, post them in the comments below. Comments are still free - we haven’t implemented the “donation” system for them yet, either.

Update: Yes, this was an April Fool’s joke. We love Dojo and that whole team… but not that much.

Get friendly with the Natives

Written By , on Tuesday, March 23rd 2010, 9:48pm

Have you extended a Native lately? It’s an incredibly helpful thing. Often people write ugly functions that take a string or whatever as an argument and return some manipulation of the string. Extending natives is a great way to do the same thing, but it is much prettier (aka: explicit, readable, easier-to-debug.)

The Difference:

I’ve seen stuff like this:

fn1(fn2(10, fn3('house')));

Hard to figure out what’s happening. Instead you can write code like:

fn3('house').fn2(10).fn1();    

A Useful, Real Example, zeroPad

I’ve used this in a couple scripts, it takes a number and returns a string with zeros padded in front: 123 becomes ‘000123’. Really handy for filenames and the like. Here’s the ugly version:

Functionally Based Example

function zeroPad(num, zeros){
  zeros = zeros || 3;
  var str = '' + num;
  zeros.times(function(){ str = '0'+str; });
  return str;
};

// usage
doSomething(zeroPad(document.getElementById('myInput').value, 3));

Native Extentions Based Example

Number.implement({
  zeroPad: function(zeros){
    var str = '' + this;
    zeros.times(function(){ str = '0'+str; });
    return str;
  }
});

// so that it works on both numbers and strings
String.implement({
  zeroPad: function(zeros){
    return this.toInt().zeroPad(zeros);
  }
});

// usage
$('myInput').get('value').zeroPad(3).doSomething();

Side by Side:

doSomething(zeroPad(document.getElementById('myInput').value, 3));
// vs
$('myInput').get('value').zeroPad(3).doSomething();

Awesome? Yes. You can do the same thing to:

Some say extending natives is a bad idea. Personally, I think it’s awesome—but this topic is a sore spot for some. Extending natives is a feature of javascript itself that any general application framework like MooTools is entitled to use. There could be an entire article dedicated to this topic but this article isn’t it. This article is simply here to show how to use this handy feature.

Flippin’ Sweet Array methods

Arian Stolwijk created this amazing gem: Array.Math. Code samples often tell the story faster:

[2,5,1,6].sum(); // 14
[2,5,6,2].product(3); // [6,15,18,6]
[9,12,15].quotient(3) // [3,4,5]

This is all made possible by extending the Array native, see?

    Array.implement({

        sum: function(start,length){
            var sum = 0, 
                start = start ? start : 0,
                length = length ? length : this.count()-start;
            length = start ? length + 2 : length;
            for(var i=start;i<length;i++) sum += this[i];
            return sum;
        },

        product: function(p){
            var arr = $type(p) == 'array';
            return this.map(function(entity,i){
                return arr ? (entity * p[i]) : (entity * p);
            });
        },

        quotient: function(q){
            var arr = $type(q) == 'array';
            return this.map(function(entity,i){
                return arr ? (entity / q[i]) : (entity / q);
            });
        },

        // and a whole lot more awesome ...

    });

Quick Tips

  • this is the number or string, or whatever, when inside the method.
  • Return something that makes sense (usually this).
  • You can implement several methods all in the same code block.

This is just one more great tool to help keep your code organized and readable.

A Better Way to use Elements

Written By , on Friday, March 19th 2010, 5:41pm

Javascript development in the browser is all about the Elements. Manipulating the DOM happens every few lines of code. It’s important enough that some libraries provide little more than DOM enhancements. Not to worry though, MooTools provides greatly in this area as well.

$ and $$

Most of you probably know the two document methods getElementById and querySelectorAll; because if you do, you understand how we select elements with MooTools methods. For those of you that don’t, you provide an ID string of an element in to getElementById, and a CSS selector string to querySelectorAll. The functions $ (which is an alias to document.id, see this post on Dollar Safe Mode for details) and $$ are basically equivalent to getElementById and querySelectorAll, respectively. Of course, since it’s MooTools, they’re more than that.

The dollar function, if given a string, will basically call getElementById on the document. If passed an element, it will just return the element, and if you pass an object with a toElement method, it will try to convert it to an element (we’ll explore that more a couple sections down). A key difference you’ll find between MooTools’ dollar function and jQuery’s is this: MooTools’ $() will only ever return 1 Element, and it will return null if no matching element is found. This means unless you’re absolutely 110% certain the element will exist, you’ll need to check the returned value before starting to call Element methods on it.

    var loginEl = $('Login');
    if (loginEl) {
            loginEl.fade('in');
    }  

The MooTools Team prefers two separate methods for the selecting elements; to remove any doubt about what a certain function call may be returning, we have one method for individual elements and another for multiple elements. In this case, it’s preferable to be explicit, instead of relying to ambiguous auto-magic. When we see $, we expect an element if it exists. When we see $$, we expect an array of elements (which, as you know, an array can always be empty). The double dollar function has some neat tricks that are explained in its own section below.

All this talk about Elements, but only about how to select them. MooTools also provides an excellent Element construction API.

new Element()

With vanilla JS (mmm, vanilla…), you’d use document.createElement whenever you wanted to create and add a new element to the DOM. MooTools tries to make the JavaScript API more pleasant to use; part of that is a more consistent and easy to use syntax and part of it is using more Object-Oriented programming practices. It feels a lot more OO when creating objects using the new keyword, whereas the standard way is more procedural.

It turns out that every element you could create inherits from the Element prototype. Specifically, the elements you create through document.createElement would be HTMLDivElement, or HTMLParagraphElement, or whichever element you create. Like I said, they all inherit from the base Element prototype, and then HTMLElement, and so on. MooTools extends the base Element class, so that all elements receive some MooTools love.

MooTools augments the Element native, providing a super-duper sweet constructor. You can provide the tag name, and then an object of properties to set on the new element. The returned object is of the same type as the $ method mentioned above. The properties you can set are fairly extensive, so check out the documentation to learn more about them, but here’s a demonstration.

toElement

The dollar method provides another function: converting the instance of class into an element(-al?) form. This is similar to a toString function, which converts objects into strings when needed. You can define a method in a class called toElement, and return an element to “represent” the instance. Let’s take a look at a snippet from a Person Class:

Several extensions in MooTools More take advantage of this, like Form.Request, Form.Validator, HtmlTable, and others. And many plugins in the Forge use this approach as well. This means that after creating an instance of one of these classes, you can just hold on to the instance in your code. Whenever you want to affect the element that the instance is controlling, you just use $(instance) to retrieve it.

Aaron even cooked up a ToElement mixin, and wrote a bit more about this over here.

Elements

I pointed out earlier that $$ returns an array-like object containing Elements. It actually returns an object called exactly that: Elements. Behind the scenes, MooTools gets an array of all the elements that meet the selector (so it’s still an array), and then extends the array with all the Elements methods. Why would we want that?

All the methods that MooTools adds to the Element native are added to the Elements class as well. You can do some pretty nifty chaining because of this. First of all, you don’t have to check that it didn’t return null. This is because any method you call on Elements, will loop through the array and try to call the method on each individual element. Even with an empty array, the loop won’t cause an error. And any method you call that would normally return a value, will return an array of the values from each element. An example should make this clearer:

    //assigns a click event to all A tags
    $$('a').addEvent('click',  function(e) {
            e.preventDefault();
            alert(this.href);
    });  

    //gets all divs with an id set, and then returns
    //an array of the IDs  sorted alphabetically
    var ids = $$('div[id]').get('id').sort();  

    //gets all divs with a UL immediately inside
    //and assigns a class name to  the divs
    $$('div > ul').getParent().addClass('has-list');

While you could put together long chains acting on all the elements you’ve selected, I’d advise against this. It certainly looks cool, and will work fine one or 2 methods out on the chain. But every method call will cause another loop through all the elements. If you’re doing a lot of things to every element, you might as well do it all in a single pass. I’ll show you what I mean.

    //this would loop through each time at addEvent, addClass, and fade
    $$('li  a').addEvent('click', function(e) {}).addClass('alertable').fade('in');  

    //whereas this will only cause 1 loop
    $$('li a').each(function(link)  {
            link.addEvent('click', function(e) {
                     alert(this.title);
            });
            link.addClass('alertable');
            link.fade('in');
    }); 

Still, when doing something simple, you can skip the each call, since Elements will handle that for you.

Concluding

MooTools provides a lot of expressive power when working with the DOM. It’s consistent API makes it a snap to add events, change styles, create elements and more. The object oriented nature of its implementation makes it so that you can extend Elements for your own purposes. Look forward to my next post where I’ll talk about extending Elements in various ways and cover best practices for when you decide to bend Elements to your own will.

Sean McArthur is a software developer at Blazonco.com who is madly in love with MooTools. Most of his contributions involve sharing tips and information about MooTools (and programming in general) at his blog and on Twitter.

More Than Meets the Eye: Form.Request

Written By Aaron Newton, on Thursday, March 4th 2010, 5:06pm

MooTools More features a diverse, powerful collection of Classes (60 plugins!!) and some are my favorite tools that I use over and over again. I thought I’d take some time to dig into some of the plugins in MooTools More that I think are interesting and really useful that maybe you haven’t had time to really sink your teeth into (or, perhaps, you haven’t found a reason to). So I’m going to take some time to talk about some of the plugins in More each month, sharing not only how they work, but how they work together and maybe even why you’d use them. Today I’m going to talk about the Form.Request plugin.

Request and Request.HTML

MooTools Core ships with three AJAX modules, two of which include element methods (Request.JSON, the third module, doesn’t alter the Element prototype). Request.js provides the Element prototype with a send method that lets you post a form (as in, $('myFormElement').send([request options go here])), and Request.HTML.js provides the Element prototype with a load method that lets you replace the contents of any DOM element with text returned from a server request (as in $('myElement').load([request options go here])). I use these fairly often, though I probably use the Request and Request.HTML constructors just as much if not more. But in my own work I found myself needing the combination of these two things; I want to submit the form and load the response into a DOM element. Turns out, I do this all the time.

Part of writing idiomatic MooTools code is encapsulating functionality into Classes. As I’ve posted before, I do this with almost all the code that I write. The only code that I author that isn’t a class (or a static object) is a DomReady statement that instantiates classes. So when I have a pattern as clear as this - submitting a form and updating the DOM with the response - it’s time to write a class.

Form.Request

Form.Request, unlike Request.HTML, is not an extension of the Request class (that’s why it’s not Request.Form). Because it is not a Request.HTML instance, it has a reference to an instance of Request in it. Form.Request’s options include a requestOptions object that gets passed along to this instance so you can configure it however you like. By default, Form.Request derives as much as it can from the form element itself. It gets its URL from the action property and the method from the method property. The user submits the form and it cancels the submit event. Form.Request inspects that event to see if the user clicked a button and, if so, sends the name/value of that button along with the data like a regular form submission. Finally, it provides an extraData option so you an send along key/values with the form in addition to those in the inputs that the user fills out.

When the form returns a response, it handles it pretty much how Request.HTML handles any other response. It injects the HTML and evaluates any scripts in the response (this is an option, too).

And what about what we set out to do? To provide a method for Element that is the combo of load and send? The plugin provides the Element prototype with a formUpdate method that works just like those two methods combined (as in $('myForm').formUpdate({ update: $('myTarget') }), which sends the form and updates $('myTarget')).

Demo Time!

Here’s a simple demo to play with. Note how our html is plain old vanilla web 1.0 form stuff. Nothing fancy. And our JavaScript is dead simple (to get the default behavior).

Getting Fancy

Hmmm. Well, our behavior here leaves a little to be desired. The main thing that seems to be missing is any indication that something is changing - that the form has been submitted and we’re waiting for a response from the server (MooShell provides a 2 second delay on the response to simulate normal web latency). We could add an event to our instance to tell the user that something is going on, like so:

Getting Fancier

Here’s where the fact that this plugin is part of MooTools More comes into play. MooTools More includes a plugin called Spinner. I’ll talk about it in depth some other time, but in a nutshell, it puts an Ajax indicator over an element that’s being updated. It integrates with Request.HTML and Form.Request configures it for us. This happens automatically (unless you disable it in the options) and all we have to do is skin it. In this example, I’ve moved our message (that we’re sending the submission) into the Spinner options.

This magic happens without much effort for us so long as we have Spinner.js in our page. This is the default behavior. We don’t even have to specify the message text if we’re content with just the spinner image.

Even More Integration

One other thing Form.Request integrates with (also in the MooTools More library, naturally) is Form.Validator. That’s another plugin I’m not going to spend a ton of time describing in today’s post - we’ll save it for a later post as it has lots of nifty things in it. But, basically, Form.Validator (and its subclasses) provide instructions for users who are filling out a form on the fly. Form.Request integrates with it so that you don’t have to do anything to make them play nice together. Both intercept the submit event and both prevent its default behavior (i.e. sending the form), except that the Form.Validator class only stops it if the form is invalid. If Form.Request didn’t respect this privilege, it would send our form even if the Form.Validator stopped the default submission event. To get them to cooperate, all you have to do is create an instance of Form.Validator on the form. Example:

In this example, we set a minLength value for our form (50 characters). The default html in the textarea is only about 45 characters, so if you just hit submit you’ll see a red error message show up. Add some more text to our example, hit submit, and the error winks out and our form sends just as before.

Appending Results

One last trick up our sleeves here; you can append results instead of overwriting the contents of our target. Think of a to-do list kind of interface, where adding a value adds a new item to a list. To get this behavior, we just substitute Form.Request.Append into our example. There are some additional options; by default it uses another MooTools More plugin, Fx.Reveal, to smoothly transition elements into view. You can also specify if the item is appended to the top or the bottom of the container. Example:

THEND

So that pretty much covers Form.Request. I hope you find it as useful as I do. If you find it useful and fun, post a link in the comments showing off what you’ve done with it. In my next post I’ll pick another plugin (or plugins) to dig into and show off their capabilities. If there’s one you’d like to learn more about, post a suggestion for my next post in the comments.

Aaron Newton is a contributor to MooTools and the principal developer of MooTools More. He is the author of the book MooTools Essentials as well as the Mootorial online MooTools tutorial. He posts (rarely these days) at his blog Clientcide.com and (much more often) on Twitter as anutron.

MooTools at FOSDEM: Video

Written By Christoph Pojer, on Monday, February 15th 2010, 10:59am

Hello everyone,

I’m really excited and pleased to announce that my presentation “MooTools as a General Purpose Application Framework” which I delivered at the FOSDEM is now available on YouTube.

If you are not able to watch the HD-Version you can download the slides here.

Thanks again to the FOSDEM team for inviting me and for giving us such a big platform to present the MooTools project. If I could name one thing that I miss already about Brussels I would certainly say the waffles…

If you enjoyed this presentation and you want me or another developer from the MooTools Core Team to present at your conference feel free to contact us.