July 16, 2007
A class is kind of a template. One of the big concepts of OO is treating your code as real world objects. Let’s say you want to have three variables for different dogs: ollie, rowdy, and killer. Each of these variables should be an instance of a class. That class’s name would be Dog. Each particular dog is an instance of the generic Dog class. I won’t go into much more detail here: there’s plenty of reading to do on what classes really are, and how to use them best.
Out of all the class systems I’ve used, I’d have to say MooTool’s class system (spanwed from Dean Edward’s Base) is the cleanest, most extensible system yet. Creating and extending classes is ridiculously easy.
(It’s also fair to note that MooTools supports Prototype’s
Class.create method as well)
You’ll notice you still get access to parent methods (through
this.parent()), as you can see where this.text gets initialized when a new instance of Dog is created.
The syntax is short, sweet, and to the point. Furthermore it allows me all the flexibility I need… well, almost. MooTools team gets bonus points for the next section.
What does this do? First off, it allows for quick, easy, extendible options. All you do is set your default options in an options property, and then call the
setOptions method inside your class. Here’s an example:
By mixing in the Options methods, you now have access to setOptions, which either uses user-defined options or class-based defaults (with one line of code).
You can also define custom events (usually called callbacks). Notice the
this.fireEvent('afterBark') bit in the Dog class above? Check it out:
It allows you to tie into the same event functionality used for the DOM, but with your own methods you create in your classes. I’m in love with this easy functionality – sure there’s been other ways to do this, but none so elegant as what the Moo team has come up with.
The last utility class is the Chain class. This allows for some nice chaining of classes: I’ll leave it up to you to explore this one since I haven’t used it in great detail yet. In a nutshell: it allows for time-dependent chains (so that events fire after another one is complete).
Object, and no overriding of parent methods. The syntax is clean and easy to remember, giving it huge bonus points in my book.