Archive for the 'Prototype' Category

Useful Utility Functions in mootools

Thursday, September 14th, 2006

The new mootools JavaScript framework has quickly impressed me with its design and usefulness. The library was clearly written to meet real programmers’ needs while working in JavaScript. Just take a look at some of the new utility functions and methods it provides.

Note: This article covers functions and methods found in the Array.js and Function.js modules of mootools.

A cleaner array iterator

Mootools provides a Prototype-inspired each method that every JavaScript array inherits. Its syntax is a bit cleaner because it’s based on the Mozilla Array.prototype.forEach method. The mootools each method allows you to pass in a second parameter as the context in which the function will be called, allowing you to resolve the this keyword. Accomplishing this in the Prototype library involves binding the function passed to each:

var x = {sum: 0};

for (var i = 0, fixtures = []; i < 500; i++) {
  fixtures.push(i);
}

fixtures.each(function(el, i) {
  this.sum+= i
}.bind(x));

// x.sum = 124750

Accomplishing the same thing in mootools is just a small syntax change (the changed line is highlighted):

var x = {sum: 0};

for (var i = 0, fixtures = []; i < 500; i++) {
  fixtures.push(i);
}

fixtures.each(function(el, i) {
  this.sum+= i
}, x);

// x.sum = 124750

The mootools each method takes the object that will resolve to this inside the loop as the second argument.

Why should you care about this minor syntax change? Because calling bind on a function every time through a loop is going to add overhead to your code’s performance. I’ve run the previous code in Firebug with a timer and the results are very telling:

500 elements each with bind: 39ms
500 elements each: 3ms
1000 elements each with bind: 75ms
1000 elements each: 6ms

Not only is the mootools syntax cleaner, but it performs almost 10 times faster than using the bind method. Keep in mind that these examples all use mootools’ each method. If I’d used the Prototype each the code would have run even slower, but that issue has already been well-documented.

Prototype each diversion

The reason Prototype’s each loop runs so slowly is that each iteration of the loop has to run through a try/catch block in order to look for break and continue statements. If you’re using Prototype’s each and you want to break or continue in the loop, you must use the following syntax:

[1,2,3,4,5,6,7,8,9,10].each(function(el) {
  if (el > 7) throw $break;
  if (el == 4) throw $continue;
  alert(el);
});

// Will alert "1", "2", "3", "5", "6", "7"

I’m not here to bash Prototype. It’s a great library. But I think it does need to be pointed out that its each method will run slower than traditional loops because of the design decision to incorporate a workaround for break and continue statements.

What, you’re not using break and continue statements? They can really help you cut down on loop iterations. There is no way to use break or continue in an each loop in mootools, so keep that in mind. You’ll have to use the good old-fashioned for loop for that one.

Running code at time intervals

JavaScript provides the setTimeout and setInterval functions for running code after a delay or at regular intervals. This comes in very handy for animations, but also for other GUI functions, such as delaying hiding a menu after navigating away. The native syntax for this can get a little verbose sometimes, so mootools provides some utility functions as methods of every function. To run code once after a time delay you use the delay method:

(function(){ alert("Sorry I'm late."); }).delay(5000);

This will run the function after a delay of 5 seconds. You can also run code at a regular interval using the periodical method:

var annoy = (function(){ console.log('Are we there yet?'); }).periodical(5000);

The previous code will run until the window unloads unless we clear the interval returned by periodical. Mootools provides a $clear function that will clear any time interval passed to it, whether it was created with delay or periodical:

$clear(annoy);

Just be sure to assign the periodical function to a variable, or else you won’t be able to clear it! Talk about annoying…

The second parameter to delay and periodical is the context object to call the function within, just like the each method. This can come in handy when using methods of mootools’ objects:

var xhr = new Ajax('url', {update: ajaxElement});
var $req = xhr.request.periodical(60000, xhr);

This code will create an Ajax object that calls its request object every minute. You need to pass the Ajax object as the second argument to periodical so the request method will run in the right context.

Cleaner object detection

Sometimes checking the type of a JavaScript object can get confusing. Everything is actually an Object, so running [1,2,3] instanceof Object returns true, even though we were checking against an array. But curisouly, running 'string' instanceof Object returns false! There’s also the typeof function, so things can get rather confusing and frustrating in a hurry when trying to detect object types. Mootools provides a function called $type that will do the proper checks behind the scenes and return a lowercase string type of the element you passed into the function. If the type of object is not matched, $type will return false.

The types returned by $type are:

  • function
  • textnode
  • element
  • array
  • object
  • string
  • number
  • false

Try it out:

$type(function(){});
// Returns 'function'

$type(document.createElement('div'));
// Returns 'element'

$type([]);
// Returns 'array'

$type({});
// Returns 'object'

$type('hello world');
// Returns 'string'

$type(4);
// Returns 'number'

Mootools just continues to amaze me. I’m digging through the source code and running lots of tests to see just how the library works, so stay tuned for more articles about this new library’s features.

Extending Objects and Classes with mootools

Tuesday, September 12th, 2006

I love the moo libraries. Despite my passion and knowledge of the Prototype JavaScript libary, I’ve never used it in a commercial project. I have used moo.fx (and the included prototype.lite) for actual client work and been very satisfied with the results. The moo libraries are very lightweight, organized and clean. They are well thought-out and extendable, and you won’t find any bloatware within.

Now Valerio Proietti has decided to grace us all with his new library, mootools. mootools is like a cross between Prototype and jQuery, with an emphasis on clean, Object-Oriented code and lean, modular design. The library has the most inspired download feature of all libraries — it allows you to pick and choose modules and automatically figures out the dependencies and compresses the code for you.

In this article we’ll take a look at one of the library’s coolest features: extending JavaScript and the library’s functionality.

Extending objects

On the surface, extending objects in mootools works just like Prototype. There is an Object.extend function that takes two arguments: destination and source.

var test = {hello: 'world'};
Object.extend(test, {animal: 'sloth'});

// test now contains "{hello: 'world', animal: 'sloth'}"

At this point mootools diverges from Prototype and adds some nice functionality to help you extend the libary and JavaScript itself.

Class inheritance

mootools implements a class inheritance scheme that is inspired by Dean Edwards’ wonderful Base class. Creating a class is similar to Prototype, but now you don’t ever have to think about the prototype object when you define the class:

var Shape = new Class({
  initialize: function(width, height) {
    this.width = width;
    this.height = height;
  },
  draw: function() {
    console.log('starting to draw...');
  }
});

Now we’ll probably never use the Shape class because it’s abstract, so let’s see how mootools lets us extend the class:

var Square = Shape.extend({
  draw: function() {
    this.parent();
    console.log('drawing square');
  }
});

Some of you may be wondering where the extend() method on Shape came from. You can breathe a sigh of relief, because it’s not coming from Object.prototype (whew!). Any class created with new Class() gets an extend method. When you use the extend method to define a child class, the parent class remains untouched. The child class inherits all of its parents’ properties and methods. Each of the child’s methods also has access to the parent’s method of the same name, accessed by calling this.parent() within a method.

To see this in action, let’s instantiate a new Square object:

var square = new Square(150, 150);
square.draw();

// Logs "starting to draw...", then "drawing square" to the console

Finally, an easy way to define classes and inheritance schemes in JavaScript!

Multiple inheritance with Class.implement()

mootools supports multiple inheritance in a Ruby mixin style with the Class.implement() method. Using the implement method of an existing class, that class can inherit methods and properties from another class or object. Unlike Class.extend(), the implement method is called on the class you are modifying, not on the object being copied. This method can be used to support multiple inheritance:

var UsefulGlobalObject = {
  inspect: function() {
    var results = [];
    for (var i in this) {
      results.push(i + ': ' + this[i]);
    }
    return results.join(",n");
  }
};

var Circle = Shape.extend({
  draw: function() {
    this.parent();
    console.log('drawing circle');
  }
});

Circle.implement(UsefulGlobalObject);

Let’s assume UsefulGlobalObject really is a useful global object. Passing this object to Circle.implement() copies all properites of the object to Circle’s prototype, so any circle object will now have the method inspect(). If we were copying from a parent class instead of an object, the syntax would use the new keyword:

Shape.ThreeDimensional = new Class({
  rotate: function(degrees, plane) {
    console.log('rotating by ' + degrees + ' on the ' + plane + ' plane');
  }
});

var Sphere = Shape.extend({
  draw: function() {
    this.parent();
    console.log('drawing sphere');
  }
});

Sphere.implement(new Shape.ThreeDimensional);

Sphere has inherited from both the Shape class and the Shape.ThreeDimensional class.

Extending library classes and native objects

Another use for the implement() method is for modifying a library class in a different code module, or even dynamically adding to a class at runtime. This is similar to Ruby, where you can reopen a class definition at any time to add new methods. We can use the implement() method to add or overwrite any method in a mootools class in our own code so that we don’t have to modify the library itself:

Ajax.implement({
  // add a new method
  newMethod: function() {
    // new method code
  },

  // overwrite an existing method
  request: function() {
    // overwrite the original request method
  }
});

This code will add a new method newMethod and overwrite the request method for the Ajax object.

One last feature of the mootools library is the concept of Native Objects. String, Function and Array have been turned into mootools native objects, which essentially means their extend() method is an alias for the implement() method. Calling extend() on these objects adds properties and methods to them just like Class.implement() does. It makes the syntax for extending a native object even sweeter:

Array.extend({
  map: function(fn) {
    for (var i = 0, a = []; i < this.length; i++) {
      a[i] = fn(this[i]);
    }
    return a;
  }
});

Any method you extend a JavaScript native object (String, Function, Array) with will have the new methods attached, even if it was created before the call to extend(). Note that the Number object is not a native object in mootools, but you can easily change that by calling Object.Native():

new Object.Native(Number);

Number.extend({
  isOdd: function() {
    return !!(this % 2);
  }
});

mootools also provides the Element and Elements classes as native objects, so they can easily be extended just as JavaScript native objects:

Element.extend({
  visible: function() {
    return this.style.display != 'none';
  },

  toggle: function() {
    this[this.visible() ? 'hide' : 'show']();
    return this;
  },

  hide: function() {
    this.style.display = 'none';
    return this;
  },

  show: function() {
    this.style.display = '';
    return this;
  }
});

The Element class in mootools contains all the methods that get bound onto any DOM node passed through the $() function. Note that if you call Element.extend(), any methods or properties you add to the Element class won’t automatically be added to any elements that have already been run through the $() function. We’ll cover extending DOM nodes in an upcoming post.

Plugin friendly

The mootools library is brand new, but it has a solid codebase that stands on the shoulders of giants like Prototype and Dean Edwards. It provides a lot of great features right out of the box, but it’s also been written to make class inheritance and object extension very simple. This encourages traditional use of class inheritance schemes, as well as adding your own extensions and plugins to the library on an as-needed basis, without having to modify the original source code.

Using Prototype’s New String Functions

Tuesday, August 29th, 2006

After years of extensive research and study, I’ve come to a profound conclusion — working with strings sucks. It’s even more difficult when you’re doing it in JavaScript. Lucky for us, the Prototype JavaScript framework provides several shiny new String object functions to make our lives easier. Sounds like a perfect chance to be lazy — let’s get to work!

Note: I’m working with the new String methods in Prototype 1.5.

Let’s create a simple string we can run some manipulations on:

var string = 'Laziness always pays off now.';

String.gsub

The gsub method is similar to the native replace method, but it’s even more powerful. It accepts 2 arguments, the first one being the pattern to search for. This can be a simple string or a regular expression. The second argument is what to replace the matched pattern with.

Let’s start with something easy. I’m tired of spaces, so let’s replace them with underscores.

string.gsub(' ', '_');

// Returns "Laziness_always_pays_off_now."

Not very exciting, and we could have accomplished the same thing with string.replace(/\s/g, '_'). Where gsub really starts to shine is when you realize that the second argument can be a function. This function will run on each match found in the string. The function receives one argument, an array of matches against the pattern. You then return a manipulated version of the string. Sound confusing? Follow the bouncing code:

string.gsub(/\s\w/, function(match){ return match[0].toUpperCase(); });

// Returns "Laziness Always Pays Off Now."

Each match is passed to the function, which can then manipulate the match and return the version to replace. We needed to reference the match as match[0] because the matches of a regular expression are returned as an array. Index 0 is the entire match, and each numeric index after that corresponds to a parenthesis group in the regular expression. If we had used parenthesis in the regular expression, we could have accessed other elements of the match array:

string.gsub(/(s|f)(\s)/, function(match){ return match[1].toUpperCase() + '-' + match[2]; });

// Returns "LazinesS- alwayS- payS- ofF- now."

String.sub

String.sub is almost identical to String.gsub, but it accepts an additional argument. Instead of replacing each match in the string, sub replaces the number of matches that you pass in as the optional 3rd argument (which defaults to 1). Let’s return to our original example:

string.sub(' ', '_');

// Returns "Laziness_always pays off now."

This time, only the first match was replaced. If we run it again and pass in the 3rd parameter we’ll see something different:

string.sub(' ', '_', 3);

// Returns "Laziness_always_pays_off now."

Otherwise String.sub is identical to String.gsub.

String.scan

The scan method simply calls the String’s gsub method with the pattern and iterator function provided. This lets you loop through each match and do something with it:

string.scan(/\w+/, alert);

// Produces 5 alerts: "Laziness", "always", "pays", "off", "now"

Another use would be to get an array of all the items that matched:

var results = [];
string.scan(/\w+/, function(match){ results.push(match[0].toUpperCase()); });

// results = ['LAZINESS', 'ALWAYS', 'PAYS', 'OFF', 'NOW']

For some reason, the scan method returns the String object split into an array of its characters.

String.truncate

This method works almost like you’d expect, with a slight quirk (in my opinion). The truncate method chops a string off to the number of characters you supply as the first argument:

string.truncate(15);

// Returns "Laziness alw..."

That’s almost what I expected to get, except there are only 12 characters from the original string instead of 15. That’s because there’s an optional second argument to truncate to append to the end of the string, and it counts as part of the returned string’s length. It defaults to ‘…’, but the following will yield the result I expected to see:

string.truncate(15, '');

// Returns "Laziness always"

Template Class

Last we have a new Template class, which I think is a work of beauty. This class lets you set up a string template with variables to replace later, much like a PHP template or the server technology of your choice. The default variable substitution pattern is: #{variable_name}. Here’s how to create an object with the class:

var linkTemplate = new Template('<a href="#{href}">#{text}</a>');

You render the template by calling its evaluate method and passing in an object with property names matching the variables you used in the template:

linkTemplate.evaluate({href: 'http://www.google.com', text: 'The omnipotent one'});

// Returns "<a href="http://www.google.com">The omnipotent one</a>"

It also works with an array:

var arrayTemplate = new Template('Original: #{0}, Sequel: #{1}');
arrayTemplate.evaluate(['Naked Gun', 'Naked Gun 2 1/2']);

// Returns "Original: Naked Gun, Sequel: Naked Gun 2 1/2"

Customizing the Template Variable Pattern

Just because we can, let’s customize the Template class even further. Say you’ve already got a nice template, but it’s written in PHP using a short tag syntax. Being the lazy programmer you are, you can’t be bothered with rewriting this. Don’t worry, your hard work now will pay off with the potential for laziness later!

The second parameter to Template’s constructor is the regular expression pattern to use for the variable substitution. This parameter is optional and defaults to the Template.Pattern constant, which allows for the very nice #{variable} syntax. We can create our own regular expression to use for template variable substitution. Try the following:

Template.PhpPattern = /(^|.|\r|\n)(<\?=\s*\$(.*?)\s*\?>)/;

Now we can pull in a typical PHP template and let Prototype work its magic:

var phpTemplate = new Template('<div id="<?= $id ?>" class="<?= $class ?>"><?= $content ?></div>', Template.PhpPattern);
phpTemplate.evaluate({id: 'news', class: ['updated', 'arbitrary'].join(' '), content: '<p>No news is good news...</p>'});

// Returns "<div id="news" class="updated arbitrary"><p>No news is good news...</p></div>"

This might be useful if you are doing Ajax calls and returning JSON data a lot. You could create a Template class when the page loads using a small PHP template from your own site, then pass the JSON object you got from the Ajax request into the template’s evalute method. Of course, only do this if the PHP template file does not have any business/application logic that you don’t want prying eyes to see. Just remember that anything you give to JavaScript can be viewed by everyone. I recommend it only for simple templates that have simple variables, if you use it at all. You have been warned.

Even though I personally prefer to use simple PHP templates, I’ll give you a Smarty pattern to play with as well:

Template.SmartyPattern = /(^|.|\r|\n)(\{\$(.*?)\})/;

One important thing to note is that you should follow the existing Template.Pattern regular expression pattern’s structure of parenthesis. This structure follows one group to match before the variable, one group to match around the variable name, and the variable name itself. If you don’t follow the (beforePattern)(varSyntax(varName)) pattern, the template won’t replace your variable properly, because it relies on these parenthesis for the 1, 2, and 3 indexes.

Coming Full Circle

Now that I’ve shown you the Template class, I can put a nice cherry on top by showing you one more trick with String.gsub and String.sub. The second argument to these methods can also be a Template string:

string.gsub(/\s/, '#{0}_');

// Returns "Laziness _always _pays _off _now."

When using a template string as the second parameter, keep in mind that the match’s index works just like the index of the array that would be passed if the second argument was a function. Here’s an example:

'Cory Hudson'.gsub(/(\w+) (\w+)/, '#{2}, #{1}');

// Returns "Hudson, Cory"

Note that this Template pattern cannot be customized like it can be when you create an object from the Template class, so you’ll have to stick to the Ruby syntax when using gsub and sub. But emulating Ruby’s not such a bad thing, is it?

Strings Can Be Fun!

Even I had fun using Prototype’s latest additions to the native String object. They can save you some time while coding, and the fact that they are so flexible with their arguments is a nice bonus!