Archive for the ‘Best Practices’ Category

How to “Pay it Back” to MooTools

August 7th, 2009 by Aaron N.

I get a lot of emails and tweets saying how awesome MooTools is. Sometimes people want to donate money or give us credit on their work in some way. Others ask how they can contribute. If you want to “pay it back” to MooTools, you can do so by:

We don’t need credit in any overt manner. Your work should be all the credit we need. We would much rather see you involved in the community than any other form of gratitude.

Using Class.Occlude to Create Singletons

July 13th, 2009 by Aaron N.

In my last article I talk about using an instance of Events to allow for loose coupling of functionality to limit dependencies as well as the use of singletons. There was a comment at the bottom of that article that I thought worth sharing and expounding upon:

I’ve been using Class.Occlude and occluding to document.body when I need a singleton. Works like a charm. – Kris Wallsmith

I thought this was a great idea and thought I’d explain what he means for those of you perhaps unfamiliar with Class.Occlude.

What Class.Occlude Does

Class.Occlude allows you to define a class that is tied to a DOM element (as most are) and to prevent that class from creating more than one instance for that DOM element. If you created a class that, say, validated a form, and you wanted to ensure that the user (the JavaScript user – not a site visitor) of your class didn’t attach two instances of that validator to the same form twice, as doing so would result in, say, a state where it was impossible to submit the form, you could use Class.Occlude to ensure that even if two instances of the form validator were created, only one would do anything. Indeed, the second time you tried to instantiate the validator class you would just be returned the first one. Here’s what it looks like:

var FancyFormValidator = new Class({
  Implements: Class.Occlude,
  property: 'FancyFormValidator',
  initialize: function(form) {
    this.element = $(form);
    if (this.occlude()) return this.occluded;
    //...the rest of  your awesome validation logic
  }
});
var fancyValidator = new FancyFormValidator($('myform'));
var fancyValidator2 = new FancyFormValidator($('myform'));
//fancyValidator === fancyValidator2

Using Class.Occlude to Create Singletons

So what Kris does (per his comment) when he wants an instance of a class but wants to ensure that there is only ever one instance, he occludes the document body. This means that even if you try and create a new instance of that class, if you’ve already created one, you’ll be returned the existing one.

For example:

var SingleFoo = new Class({
  Implements: Class.Occlude,
  property: 'SingleFoo',
  initialize: function(arg1, arg2, etc) {
    this.element = $(document.body);
    if (this.occlude()) return this.occluded;
    //the rest of your stuff goes here
 }
});
var foo1 = new SingleFoo(a1, a2, etc);
var foo2 = new SingleFoo(b1, b2, etc);
//foo1 === foo2

A clever solution, if you ask me.

Singletons and Event Arbiters

June 23rd, 2009 by Aaron N.

I got an email today asking about how I use singletons in my own development environment and I thought I’d post my response for anyone who might find it useful.

Here’s the question:

Whats the best way to define some
code, assign it to a global object and have it run all at once?

I use MooTools server-side quite a bit in my ASP code using JScript
and we have need for global singleton objects to be around (such as
our logger). As there are no clear best practice ways out there of
doing it I’ve started and stuck with something like this:

var LoggerObject = function() {
// Logger code
}

var Logger = new LoggerObject()

which is ok but feels like I’m missing something. How do the pros do
it, whats the advantages/disadvantages to other methods?

Now, for those who aren’t familiar with the concept, a singleton is a class that designed to have only one (or, perhaps, a limited number greater than one) instance. In JavaScript, any object can inherit from any other object and you can’t really prevent this, so in the truest sense of the term, there’s no such thing as a JavaScript singleton.

MooTools gives us a function called “Class” which helps us manage inheritance between objects. Creating an object that is an instance of a class is done with the “new” operator:

var myWidget = new Widget()

If you wanted to create a class and immediately cast it into an instance, you could do the following:

var myInstance = new new Class({...})

The double “new” invokes the function returned by class and returns an object – an instance of that class. There’s rarely a reason to do this. In fact, the only reason I can think of is if you want that class to extend another:

var myInstance = new new Class({
    Extends: SomeOtherClass,
    //new properties go here
});

The problem with this pattern is that it doesn’t really get you much. JavaScript is all about objects, and there are better ways to accomplish this task.

I use objects (as singletons) all the time for my application code (almost never for plugins obviously; those are meant to be extended and instantiated). I often use a “site” object to attach methods and manage state (such as if the user is logged in, their username, etc). I just make this a plain old JavaScript object, like so:

var mySite = {
    login: function(username){ this.username = username; },
    showWelcome: function(){
        $('welcome').set('html', 'Welcome ' + this.username);
    }
};

There’s nothing special here – this is how JavaScript works. It’s important to note that classes in MooTools exist to give us functionality and to let us derive functionality through inheritance. If I create a class called Widget and I later want to make a version called Widget.Ajax, I can extend Widget and add only the ajax parts. With singletons, the whole point is that you aren’t going to create more than one of them.

However, there are some other things that MooTools’ Class gives us, such as mixins (classes that are meant to use Implement to imbue the target class with their properties). Examples here include the Events and Options mixins that give instances methods like setOptions and addEvent. In these cases you can still use the object declaration above and then extend the object:

var mySite = {
    login: function(username){
        this.username = username;
        this.fireEvent('login');
    },
    showWelcome: function(){
        $('welcome').set('html', 'Welcome ' + this.username);
    }
};
$extend(mySite, new Events());

Working this way obviates the need for the clunky “new new Class” pattern and it’s more intelligible in my opinion.

Event Arbiters

Which brings me to a common practice I use when I build applications. When I build a site or application I try to make things as modular as possible. I make it so that my site works without any JavaScript first, then I start adding in the UI goodness with ajax and animations and sortable tables and all that jazz. I also make the JavaScript itself modular. Everything that can be a class I make a class. The stuff that’s left over is the code that instantiates those classes.

But what if the code that instantiates one widget needs to get information from another widget? For instance, what if our Welcome widget needs to know the state of the Login widget? Well, if our Login widget stores it’s state on the mySite object, then the Welcome widget can just inspect that, right? That’s cool; if the page loads and mySite.username is undefined then the Welcome widget knows the user isn’t logged in. All good.

But what happens when that state changes? What happens when the user logs in? Now we need an event – onLogin or something, but that means that Welcome needs to attach itself to Login and now we’ve lost some modularity because we’ve introduced a dependency. Welcome can’t work without Login. In this case, this doesn’t seem like a bad dependency to have – after all, a welcome message without login functionality doesn’t make much sense – but there might be dozens of other widgets that need to do things when the user logs in and we may want those widget to work even if the user doesn’t log in. Further, we may want to load the Login widget only on demand – when the user tries to log in for example. We can’t do that if all our widgets need to attach events to the Login widget.

This is why I make mySite an instance of Events. mySite doesn’t really have any native events per se. Rather, other classes attach events to it and fire events for it. So, in our puzzle above about our Login widget, instead of all the other widgets attaching an onLogin event to Login, they can attach it to mySite, and then our Login widget fires that event not on itself but on mySite:

var mySite = new Events();
var Login = new Class({
    //...login logic and stuff
    loginSuccess: function(username){
        mySite.username = username;
        mySite.fireEvent('login');
    }
});
var Welcome = new Class({
    initialize: function(){
        this.showMessage();
        mySite.addEvent('login', this.showMessage.bind(this));
    },
    showMessage: function(){
        $('welcome').set('html', mySite.username ? 'Welcome ' + mySite.username : 'Please log in');
    }
});

Now our classes are no longer dependent on each other. They are both dependent on mySite but that was always the case. They can each come and go as they wish without really caring about the other. This increased modularity pays off later as your site grows in complexity. Some pages may have some widgets and some may have others. You can attach logic to the mySite object without having to really manage those dependencies.

Exporting Files From Git (similar to SVN export)

April 25th, 2009 by Aaron N.

I use git for just about all my code now. For some of my work, I need to export portions of or all of a git repo into some other location without picking up all the git files themselves. This is the way svn export works. There are two ways I do this. One is using git archive. This command always returns a zipped up copy of the repository, so you have to pipe it over to tar if you want to export files (either that or save the tar file and then in a second command extract it). Here’s my one-line command for taking the archive and sending it to a different location:

git archive HEAD | (cd ~/path/where/I/want/it/ && tar -xvf -)

This will extract the ENTIRE library to the specified path (without the .git files and whatnot).

Sometimes, however, I want to pull out just a portion of the library. git archive always gives you the whole enchilada which kinda sucks, and in this case I use rsync, like this:

rsync path/I/want/to/export/ -ri --del -m --exclude ".*" ~/path/where/I/want/it/ |grep sT

That last bit – the grep sT will limit the output of what I see so that I only see the files that are updated. I use that just to sanity check my export. If I see a TON of stuff go to update a path that already has the library and I know I only changed one file, then I know I got the path wrong.

Clientside Image Compression

April 1st, 2009 by Aaron N.

Over the last year of consulting I’ve done several jobs where I didn’t have access to the images used by the site. In one case it was 3rd party software and I was just enhancing the user experience through JavaScript, in another case the images were created dynamically by the server. In yet another case I worked on a site that had editors uploading photos all the time.

In each of these cases it became apparent that the images were never optimized by the people creating them (or, in the case of the machine, by it). I got inspired by smush.it which was demo-ed at the Ajax Experience last year in Boston and spent some time picking apart PNGCrush (an open source image cruncher) and have put together a rather robust solution in JavaScript.

Introducing the JavaScript PNG Resizing Image Library

The JavaScript PNG Resizing Image Library (a.k.a. JPRIL) is easy to use. Just include the library in your document and it will find all the PNG files on your page and compress them for you. You can also call JPRIL directly on a PNG file (for images loaded by JavaScript after the page loads) like so:

JPRIL('myPngElementId')

It’s that easy.

The Output

JPRIL automatically replaces any PNGs in the document with it’s compressed version, garbage collecting the older, larger version. The images look about the same, but how compressed they are is up to you. You can pass in a second argument which is treated as a percentage for compression. Here are two examples:

jprilfools

Download

The code is of course open for anyone to use. Just click here to download it. Compressed and gzipped it’s only 62K.

Update

Yes, this is an April fool’s joke.

Update Update

…someone actually made it: http://ajaxian.com/archives/javascript-jpeg-encoding

Sly, the Latest CSS Selector Engine

March 25th, 2009 by Aaron N.

There’s been a lot of churn on selector engines in the last six months or so. The jQuery guys released a stand alone library (Sizzle) which was adopted by a lot of other frameworks (it’s now a part of the Dojo Foundation) including Prototype, Dojo, jQuery (obviously) and others.

There was a lot of hullabaloo when MooTools decided not to use it. One of the arguments that Valerio made in his post about that was this:

Let’s face it: every selector engine, every part of our libraries has benefited from the others. Where they diverge is not an indicator of which framework is superior to another. Rather, they are differences in philosophy. If everyone were to use the same, shared codebase, these awesome open source contributions and general advancements will stop, and users wouldn’t be able to choose the approach which works best for them. I don’t want to see that happening.

That notion – that if all the frameworks adopted the same selector engine that both innovation will suffer – was refuted generally by the advocates of everyone using Sizzle. John Resig left a long and thoughtful comment on my post about Sizzle that included this statements:

With so many minds at the table (all the major libraries) it’ll mean that this library will be in front of the majority of JavaScript users, in one way or another. It will be compelled to become faster.

Frankly, not using Sizzle will mean that MooTools will always be playing a game of catch-up. … Right now jQuery, Prototype, Dojo, and YUI are all looking at using the library – that only leaves one odd library out. I’m not attempting to put undue pressure on your team – it’s absolutely your decision – but you’ll definitely be in a position, if all the libraries use Sizzle, of constantly trying to catch-up to what is implemented in the de facto implementation.

I refuted this statement and so did members of the MooTools communities (and others). John’s argument that because MooTools is the odd one out that we’ll always be playing catch up seemed especially off the mark, because it implies that Sizzle will, by virtue of having so many people using it and contributing to it, always step ahead of MooTools, and that all MooTools would hope to do is catch up – that is, implement changes to match Sizzle’s progress rather than out pace it. In reality, that’s not how technology moves forward; competing parties take turns passing each other and drive the baseline forward.

Well, today it looks like it’s Sizzle’s turn to play catch up.

Introducing Sly

MooTools contributor Harald Kirschner today released his own selector engine, Sly. This is a stand alone library (much like Sizzle) that is only 3K gzipped (8K minified without gzip). This is on par with Sizzle (which claims that gzipped is 4K). It offers the same sort of flexibility and support for custom selectors plus all the CSS3 selectors. Form the announcement article on Harald’s site.

If you’re a code geek like me, you might want skip the details and go directly to the source, the speed tests or the specs.

Sly awesomeness:

  • Pure and powerful JavaScript matching algorithm for fast and accurate queries
  • Extra optimizations for frequently used selectors and latest browser features
  • Works uniformly in DOM documents, fragments or XML documents
  • Utility methods for matching and filtering of elements
  • Standalone selector parser to produce JavaScript Object representations
  • Customizable pseudo-classes, attribute operators and combinators
  • Just 3 kB! (minified and gzipped, 8 kB without gzip)
  • No dependencies on third-party JS libraries, but developers can override internal methods (like getAttribute) for seamless integration.
  • Code follows the MooTools philosophy, respecting strict standards, throwing no warnings and using meaningful variable names

But what you probably care about most is the performance:

But enough babbling: I know you just want speed and validity results. The following results were measured using a list of frequently used selectors, searching on a copy of yahoo.com, running in slickspeed.

compare2

(See also the DOM fragment speed graph) If you are interested, run the various speed tests on your own system and post your results.

The adapted version of slickspeed also supports other test cases, like querying on a DOM fragment or an XML document. They make sure that Sly and other engines work the same in all environments.

Wait, But This Isn’t MooTools?

That’s right. This is a project Harald was working on and finished and released. This isn’t the official MooTools selector engine and won’t be. MooTools has it’s own new selector engine that is in development. I won’t go into why MooTools isn’t working on a different one (I’ll leave that to its authors to discuss when they are ready to), but the basic point is valid here: having more than one of these things is good competition and it moves the base line forward. Harald’s work has fed directly into the MooTools engine and, perhaps, will also influence Sizzle, who knows.

Why It Kinda Doesn’t Matter

I’ve been saying for a while now that the speed of selector engines is just not an issue any more. The speed of the current selector engines of jQuery, MooTools, and Sly look pretty different on a graph next to each other, but they are all blazing fast. Compared to what they were like a year ago, all of them are miles ahead now and at this point we’re quibbling over milliseconds. There are other things we need to optimize and selector engines are, at this point, plenty fast for nearly all tasks. That’s not to say that there isn’t always room for improvement, but at this point it’s more about features and flexibility than it is speed, and to a great extent all these engines are extensible, flexible, and powerful.

I’m happy to see people out there still cracking this problem open to look at it from fresh perspectives and I’m sure it’s gratifying to write something that performs better than the competition. Congrats to Harald for a fine job well done.

Don’t Repeat Your Moo

March 2nd, 2009 by Aaron N.

There’s a fantastic post over on devthought by MooTools developer Guillermo Rauch that I just had to share.

Given the Object-Oriented nature of the MooTools framework, code repetition is something that is long forgotten (or should be) in the scripts your write. With the avoidance of code repetition comes code reusability, which results in your website being easier to read, extend and maintain, and your scripts smaller in size.

At this point there’s no doubt in anyone’s mind that DRY is a principle we should stick to. However, let’s examine how to achieve this in the right way.

MooTools Powered CSS Sprites

February 19th, 2009 by Aaron N.

A few months back David Shea wrote an article on A List Apart about CSS sprites that inspired Uruguayan MooTools developer Gonzalo Rubio (aka gonchuki) to take the practice and apply using MooTools:

While the original version used jQuery (1.2.6 at that time) and lots of people like it, we (mootoolers) have a different approach to code specially emphasizing on OOP techniques and readability. Part of the issue might not be jQuery per-se and be Dave’s code that was a little obfuscated, but it anyways has a lot of room for improvement.

This article will just describe differences between the MooTools implementation and the Dave’s jQuery one, so unless stated otherwise, everything from the ALA article applies here.

new Sprites2({mode: 'fade', item_selector: 'ul.nav a', duration: 250});

(this is just a screenshot from the post)

picture-21

Check out the full post for details and to download the code.

Comparing Frameworks with Inheritance Benchmarking

February 19th, 2009 by Aaron N.

Over on Ajaxian yesterday was a post about benchmarking inheritance methods that was pretty interesting (here’s the post that Ajaxian was covering). In it, various methods for extending objects in JavaScript are compared:

  • Ad hoc inheritance – This is a common(?) homebrew technique for allowing prototypes to leverage the code in objects further up the prototype-food chain. Methods are overridden by keeping a reference to the parent method in a separate property , which can then be invoked as needed. It’s fast but not very pretty, and it’s arguable whether or not this qualifies as real “OO” inheritance.
  • Prototype-style inheritance – Prototype uses a strategy inspired by Alex Arenell’s Inheritance library. Subclass methods declare a “$super” argument that is set up by Prototype to reference the superclass’ method.
  • Base2-style inheritance – Dean Edwards’ library. Subclass methods invoke “this.base()” to call their superclass’ implementation.
  • John Resig inheritance – JR, of jquery fame, experimented with a Base2 variant which he published on his blog. It’s a bit simpler than Base2, but seemed worth testing.

Read the rest of this entry »

Designing Web Interfaces

February 10th, 2009 by Aaron N.

I haven’t had a chance to read this yet, but I’m going to go ahead and suggest you go get a copy of Bill Scott’s book, Designing Web Interfaces.

You should also watch this presentation, on which the book is likely based. I saw him give this talk at Google and then brought him in to CNET to give it again to our crowd.

Bill Scott was the lead user experience evangelist at Yahoo and is now at Netflix. He’s an interesting mix of good engineer and good experience designer and I’ve spoken with him on numerous occasions about various challenges and he always gives great insight.