Mootools Short-cuts Part II

This article, which is a follow-up to How well do you know Mootools?, will be geared more towards Mootools syntax, using right and wrong examples within the Mootools framework, though some of these examples may apply to other libraries. Here we go.

Setting Multiple Styles/Properties/Events

Wrong

$('foo').setStyles({
  "backgroundColor": '#f00',
  "color": '#fff'
}).setProperty('href', 'new_href').setEvents({
  "mouseover": doSomething,
  "mouseout": doSomethingElse
});

Right

$('foo').set({
  "styles": {
    "backgroundColor": '#f00',
    "color": '#fff'
  },
  "properties": {
    "href": 'new_href'
  },
  "events": {
    "mouseover": doSomething,
    "mouseout": doSomethingElse
  }
});

While the first example isn’t too bad, all the chaining really isn’t necessary if you just use set(). I’d say it looks a lot nicer, too.

Creating New Elements

Wrong

new Element('a').setStyle('color', '#fff').setProperty('href', 'new_href').addEvent('click', doSomething);
new Element('a', {
  "href": 'new_href',
  "styles": {
    "color": '#fff';
  },
  "events": {
    "click": doSomething
  }
});

This is similar to the previous example, except you can set all the values upon the creation of the element. Note that properties don’t have to be contained in a properties object.

Ajax Forms

Wrong

new Ajax('my_action.php', {
  "data": $('my_form').toQueryString()
});

Right

$('my_form').send();

That’s a pretty nice short-cut I’d say. It’ll read the form’s properties and insert them accordingly. For example, the form’s action property will be used as the url for the Ajax request.

Selecting Elements

Wrong

$('my_ul').getChildren().getFirst();

Right

$$('#my_ul li a');

Let’s say we have a navigation list and we want to get all the links in it. While the first method is pretty short, CSS selectors are shorter, and according to my tests in this case, faster.

Resetting the Class

Wrong

$('message').removeClass('error').removeClass('alert').addClass('alert');

Right

$('message').setProperty('class', 'alert');

I know this might seem obvious to some, but sometimes we get so caught up in the library’s special functions that we don’t always think of the simplest solution. It’s happened to me.

Conclusion

That’s all I can think of for now. I’ll have to scour the forum for more misuses. Feel free to post any below (wrap your code in a pre element with a lang attribute equal to “javascript”).

3 Responses to “Mootools Short-cuts Part II”

  1. Moober

    =) nice Work.
    im starting out at this =)
    it would be helpful

    =)

    Kind regards

  1. hosthg » Blog Archive » Mootools Short-cuts Part II
    Pingback on November 14th, 2007 at 3:44 am
  2. Learning MooTools: 20 MooTools Tutorials and Examples | [w3b]ndesign
    Pingback on August 17th, 2008 at 6:13 pm

Leave a Reply