Posts Tagged ‘prototype’

Using Sizzle with Prototype

March 24th, 2009

Recently, John Resig of jQuery fame released the selector engine used in the new version of jQuery called Sizzle.  Sizzle is a new take on using CSS selectors within Javascript and aims to be far more efficient than the methods commonly used by most current Javascript libraries.

Currently, I'm working on a large project that is nearly ready to deploy.  Most of the Javascript for this project has been written using the Prototype framework; however, we wanted to leverage the speed of the new Sizzle selectors engine in our project.  Given that we are deep in the QA process of the project, large code changes are discouraged to ensure code stability.  What we needed was a quick way to integrate Sizzle with Prototype.

The following code can be added to your Prototype 1.6.x file and will ensure that prototype's main element collection methods (Element#select and $$) both use Sizzle.  I've written before on how slow $$ can be, so these are two quick wins for Prototype performance.

//Overwrite findChildElements to use Sizzle http://sizzlejs.com
Selector.findChildElements = function(element, expression){
    expression = expression.join(", ");
    var results = Sizzle(expression, element);
    if(results.length > 0){
        for(var i=0; i < results.length; i++){
            results[i] = Element.extend(results[i]);
        }
    }
    return results;
};

Prototype Basics: Creating a Javascript Class

September 24th, 2008

Javascript is, by it's nature, not an object oriented language.  However, everything in Javascript is an object.  So what you have are using objects to write procedural code; a truly intriguing concept.  It brings to light that having objects does not make a language object oriented.  Today I want to talk about the other two important concepts of object-oriented programming in Javascript--classes and inheretance.

In object-oriented programming, a Class is used to define an object; that is, it defines what characteristics an object has (its properties) and what it can do (its methods).  Javascript does not allow for either of these concepts in its native implementation (though we can work around this limitation with some clever programming that I'll cover in another article).  Today I want to look at how the Prototype library provides an easy way for developers to create and extend classes and objects of those classes.

We're going to start with creating a basic class.  Most tutorials at this point degenerate into some silly example involving a car, or an animal.  Given that I'm trying here to provide some real world perspective, I want to look at something we might actually try to implement.  In this case, we'll use a photo viewer.  We want to set up a viewer that can be passed a photo and display it.  Then, we'll use inheretance to extend the class to allow for effects.

Creating a Basic Class

var PhotoViewer = Class.create({
    initialize: function(){
    }
});

There are two important things to note in this example:

  1. The Class.create() method is a prototype method that sets up a class for us.  The primary benefit we get from this is that the class can extend another class (which we will do shortly).
  2. When a new object of this class is created, it will automatically call its initialize method.  In Prototype, initialize is the class constructor.

Now we need to add some methods to our class:

var PhotoViewer = Class.create({
    initialize: function(){
        this.photoContainer = $('container');
    },

    showPhoto: function(url){
        var imgEl = new Element("img", {src: url});
        this._show(imgEl);
    },

    _show: function(imgEl){
       this.photoContainer.update(imgEl);
    }
});

So now we've created our first class using Prototype.  The showPhoto() method is a public method that can be called from outside the object.  A URL for an image is passed into it and a new image element is created using that URL.  The _show method is a "private" method that cannot (in this case, should not) be called from outside the object.  It handles the displaying of the element.

Note that Javascript has no concept of public vs. private methods; therefore users could technically call this method wherever they see fit.  The _methodname convention is sometimes used to denote that a class should be considered private by developers and thus not called.

Extending a Class

Now that we have created our basic PhotoViewer class, let's create a class called AdvancedPhotoViewer that extends PhotoViewer to add animation to the image loading.

var AdvancedPhotoViewer = Class.create(PhotoViewer, {
    initialize: function($super){
        $super();
    },
});

There are again two important new concepts introduced here:

  1. Notice that the Class.create() method now has two arguments, the first is the parent class.  By defining a parent class, our class now has access to all of the properties and methods of its parent.
  2. The $super() method calls the method within the parent class that has the same name as the method in the child class.  By calling $super() in the initialize method of our AdvancedPhotoViewer, we call the initialize method of the parent class.  Were we not to call $super() on a method that has an identically named method in the parent class, the method would overwrite the parent method (which there are many times you want to do, which is why this is left for you to decide whether or not you wish to perform all of the tasks from the parent method first). You will see an example of this in a moment.

Now we want to add some animation using Scriptaculous.  We want the element to begin hidden and then appear using a fade-in transition.  For this, we can override the _show() method to call our animation rather than simply calling update():

var AdvancedPhotoViewer = Class.create(PhotoViewer, {
    initialize: function($super){
        $super();
    },

    _show: function(imgEl){
        /* Notice we don't call $super as we want to override the original method */
        this.photoContainer.insert(imgEl.hide());
        new Effect.Appear(imgEl, {fps: 50, duration: 0.5});
    }
});

As you can see, we've added code which will cause the element to fade in rather than simply appearing.  Notice also that even though we never explicitly created it within the AdvancedPhotoViewer class, we can access the this.photocontainer property because we called the parent constructor that defines it.

So there you have it; a brief tutorial on creating and extending classes using Prototype. I hope you found this tutorial helpful. Please feel free to post any questions you may have in the comments section.

Which JS Framework is “The Best”

June 27th, 2008

After my recent tutorial was posted on NETTUTS, I found the feedback filled with comments such as:

Jquery is the best and can be used to do all of this stuff plus more.

and

Yeah, I agree NETTUTS should only go away from jQuery when it can’t perform something

Reader Tim commented:

Nice. but which is best? Scriptaculous, Mootools, jQuery, or Dreamweaver CS3 built in apps?

What amazes me is not the sentiment so much as it's the nearly religious zeal with which these people are dedicating themselves to a code library.  So I wanted to take a moment to examine the question without that same type of bias--Which JS Framework really IS "the best?"

To attack this problem, we should first really define what "the best" means.  After all, if some code library is worth this type of devotion, I want to be pretty damn sure that it's the best!  So what does it mean to be the best Javascript library?  Here are some thoughts:

  1. It's the smallest
  2. It's the fastest
  3. It provides the most functions
  4. It provides the strongest application structure
  5. It provides a plugin system
  6. It provides clean methods to implement Object-Oriented Programming
  7. It integrates with a powerful back-end development platform
  8. It provides easily maintainable and extensible code.
  9. It's the most widely adopted by the biggest sites

That list was literally written in 30 seconds off the top of my head; I'm sure the true criteria to establish which Javascript library is the best is a far longer list.  That said, we'll use these 9 criteria.   What do we notice about these requirements?  If you answered that some of them lie in nearly direct opposition to each other (such as 1 and 3) you're right.  If you answered that some of them can compensate for weaknesses in other areas (for example, 5 or 8 and 3) you're also right.  Even with a short list of 9 requirements, we know two things:

  1. No one library is going to meet all of these criteria
  2. Not all of the requirements are always requirements

If you're busy debating which Javascript framework is "best," you're fighting a religious war that cannot be won; simply put--no one Javascript library can be objectively defined as "the best."

Gee, thanks Brian.  But which should I use?

In my opinion, for every project, you should evaluate which library makes the most sense to use.  It is certainly reasonable to have a preference (for example, you may feel that jQuery works for about 75% of all the project work you do) and that's great.  You may even find areas of overlap where you continue to use your preferred framework simply because it makes sense. For example, if you know prototype very well but are less experienced with jQuery, you may want to choose to use Prototype in the interest of speeding development even if based solely on the requirements of the project jQuery would be a "better" choice.

My personal opinions

Since you're reading my blog, I will give you what I consider to be my reasonably well-informed personal opinions of the libraries I have worked with and when they make sense:

The library I'm most experienced with is Prototype.  The primary reason is that it is the library we have standardized on here at AutoTrader so I work with it extensively on a daily basis.  My feelings on Prototype are that it is a great library that provides a lot of great functionality, is for the most part reasonably quick (with some notable exceptions).  Both jQuery and MooTools have their roots in Prototype, so moving between those 3 libraries are probably easier than moving to and from others.  For general development, my familiarity with Prototype makes it my first choice.  The biggest thing Prototype has going for it is its implementation of classes and inheritance easing the transition for those very familiar with object oriented programming.

For everything I like about Prototype, I dislike Script.aculo.us.  The way its implemented seems silly to me (creating a new object for each effect is how you execute the effect?) and it doesnt "fit" well with Prototype's code style.  It lacks an implementation of Robert Penner's easing equations which make its animations look less impressive.

I have a strong love of jQuery; it's incredibly small, incredibly fast, and very much follows the paradigm of "get out of the way."  The plugin architecture is fantastic, and the jQuery UI library is great--fully integrated with the jQuery style of coding and integrates everything I'd expect from a fully-featured animation library.  These guys have taken the concept of dereferencing objects to an extreme level--and it can make jQuery code difficult to read at times when you have one line that chains 35 methods.  That said, once you understand its power; its actually quite elegant.

MooTools is another great library, and if you're looking to do a lot of heavy animation work, I'd even suggest it over jQuery.  MooTools began as an animation extension to Prototype that evolved into its own library--but their heavy focus has always been on providing the fastest, smoothest animations of any library.  Obviously its not limited to only animation work; but that's certainly where the bulk of its strength lies.

I'd also like to mention SproutCore--if your goal is to build a fully functional application within a web browser that relies less on Ajax and animation and more on solid application architecture, SproutCore appears to be an excellent choice.  I have far less experience with it than other libraries, but from what I've seen, it's MVC implementation is quite impressive!

I'll refrain from in-depth comments on other libraries with which I have no experience--but there are certainly a multitude of choices out there!

Always remember to take your requirements for the library into account on a project-by-project basis--and don't be afraid to work with multiple frameworks.  It only makes you that much more valuable to an employer!

Accordion Tutorial on NETTUTS

June 11th, 2008

Several of the websites produced by Eden have become perennial favorites in my RSS reader, including FlashDen, PSDTUTS, and most recently, NETTUTS.  Recently, I wrote a tutorial for NETTUTS that you can check out on their site, it's titled Create a Simple, Intelligent Accordion Effect Using Prototype and Scriptaculous.  While you're there, I highly recommend checking out some of the other great content they have.  Many talented folks have contributed tutorials for them, and the site is really establishing itself as one of the premier web development blogs online.

Method & Function Binding in Prototype Javascript

June 6th, 2008

Over the past few days, I've been asked by several colleagues about Prototype's bind() method; what exactly it does and when it should be used. In short, method binding in prototype allows you control the object that the keyword this references within a given context. Binding is a fairly complicated topic that, as I'm writing this post, can be as difficult to explain as it is to understand. However, once you grasp binding, it will seem perfectly natural to you.

To understand binding, you first have to understand a fundamental concept of Javascript: everything is an object. Every function, every element, every string, every array; at their basic level, they are all objects.

The next thing you must understand is what the keyword this means in object-oriented programming; this always refers to the current object. Consider this snippet:

Class TestClass{
  private int testInt = 0;
  public int getTestInt(){
    return this.testInt;
  }
  public void setTestInt(int myInput){
    this.testInt = myInput;
  }
}

In this brief Java example, we can see the use of the this keyword. In plain english, this corresponds to the object saying "This is my value."

This is where it becomes important to remember that everything in Javascript is an object. That means any time we create a function, we are creating an object. The keyword this will refer to the function; not its class. So when does this affect us using prototype? Most often, if affects us any time we use a closure such as in this example:

var Person = Class.create({
  initialize: function(name){
    this.name = name;
    var myArray = $('submitform').getInputs('text');
    myArray.each(function(textbox, i){
      /* this.processFormFields doesn't exist, because "this" refers to the
         anonymous function we've created as a closure */
      this.processFormFields(textbox);
    });
  },
  processFormFields: function(textbox){
    /* do some stuff here */
    /* This will not work, because in this case, this will refer
       to the closure, not the class object */
    textbox.value = this.name;
  }
});

In this case, we can't access methods of our person-classed object from within the closure object. So how can we run the class method from within the closure? Method binding!

Prototype's bind() method allows us to specify the object with which to associate the this keyword. Most often, you'll want to bind the method to the classed object you're working with as in this modified example:

var Person = Class.create({
  initialize: function(name){
    this.name = name;
    this.age = 0;
    var myArray = $('submitform').getInputs('text');
 
    var boundProcess = this.processFormFields.bind(this);
    myArray.each(function(textbox, i){
      /* boundProcess() is a copy of processFormFields that is
         specifies that THIS refers to the class object--not the closure */
      boundProcess(textbox);
    });
  },
  processFormFields: function(textbox){
    /* do some stuff here */
    textbox.value = this.name;
  }
}

Notice two important things here. First, we've used the bind() method. It has created a copy of the processFormFields method that will be able to be used from within the closure (since it does not rely on the this keyword to be called). Second, it has associated itself with the class object; which means that within the method, this.name will refer to this.name within the class object and not look for it in the closure (which would simply be undefined).

The general rule: any time you need to use one of your class methods within a closure and that class method will refer to any class properties using the this keyword, you need to bind that method to the class object.

One of the times that this becomes the most obvious is in event handling. Suppose we add this method to our class above:

eventHandler: function(e){
  this.age = e.element.identify();
}

And we observe it on a click of the "myButton" element:

$('myButton').observe("click", this.eventHandler);

In this case, the context of the event handler will be the element on which the event handler was called. Since myButton does not have a property called this.age, an error will be generated. We need to bind the method to the class object, not the myButton object. However, because this is an event handler, we will use prototypes bindAsEventListener() method which works exactly like bind--except the returned function automatically accepts the event object as its first parameter.

$('myButton').observe("click", this.eventHandler.bindAsEventListener(this));

Now, using this.age in the eventHandler() method will reference the class property age rather than a property of the element on which the eventHandler() was fired.

It's all about context!

Remember, the purpose of method binding is to ensure that you can make use of the "this" keyword. Without access to this, you lose the ability to work effectively with your class objects.

Performance is in the Details

May 29th, 2008

This past week, some colleagues and I sat around a brainstorming table trying to isolate what was causing a particular page to load incredibly slowly in Internet Explorer 6. Drawing on our combined years of experience, and our mutual disdain for IE6, we came up with what we believed to be a solid list of potential bottlenecks that included (among other things):

  1. DOM Parsing (the DOM is very large for this particular page)
  2. Slow / Inefficient Ajax requests
  3. Parsing large JSON strings returned by Ajax request
  4. Too many event handler assignments

We tested each of these theories among the 5-6 others that we had collected and could not find any particular area that was acting particularly slow. Unfortunately, the lack of any serious profiling tools for IE made the task of doing real benchmarks almost impossible. We scratched our heads and adjourned for our 3-day weekend.

In the process of fixing random software defects, one of our other lead engineers stumbled across this line of code that one of our more junior engineers had checked in:

for(var i=0; i < $$('div.contents').length; i++)

My head was spinning just looking at that one statement. For those unfamiliar with Prototype, the $$ method is a sometimes useful, but horribly inefficient means of searching the DOM. In plain English, this method will walk the entire DOM of your document, and check if it matches the CSS selector contained within, and add a reference to that element to an array if it does. When the traversal is complete, the array is returned. Do you see the problem now? Each time the loop ran (conceivably 50+ times in this case, however many elements matched div.contents) it would have to do an entire DOM traversal. Additionally, it would have to calculate the length of the returned array each time!

For reference, as a service to all of the other engineers-those who don't yet know as well as those who have had to clean up after someone who didn't know, better practice would be:

var contents = $$('div.contents');
var length = contents.length;
for(var i=0; i < length; i++)

However, it would be far more advisable to restrict your search of the DOM using prototype's Element.select method to only check the portions of the DOM.

The important take-away here is that you need to exercise extreme caution when using any method that traverses the DOM; especially as long as IE6 is a large player in the browser market as its DOM traversal is notoriously slow. Prototype's $$ is an especially dangerous method (even when used properly) and should only be employed in cases when it truly makes sense—that is, when you need to check the entirety of the document. Far more often, you will know a containing element from which to base your search:

var oddRows = $("container").select("li.odd");

Finally, always remember to calculate all of your parameters outside of a for statement (as in example 2 above). Doing so as part of the statement frankly reeks of the kind of amateur development practice one might get from reading a collection of some of the worst technical books on the market as for some reason they all seem to advocate this kind of thing.

DOM Traversal is expensive. Know what you're looking for and determine the best way to find it; not the easiest.

JavaScript Event & Event Method Bugs and Workarounds

May 14th, 2008

Today I spent a good deal of my time dealing with Javascript event handling and delegation using the Prototype javascript library with relation to some forms in our current project. In addition to simply firing and catching events using actual events, this applications also make use of the click() and focus() methods to fire these events in certain circumstances without user interaction. The issues I'm discussing here are specific to radio buttons and checkboxes across the three major browsers--but primarily focused on Firefox and Safari. The provided example does not use Prototype--it is plain vanilla Javascript. However, the proposed workaround does rely on the Prototype library (sorry, it was just faster that way--and it's also the implementation I used to solve the problem on my own).

What (I believe) the spec calls for:

When a radio button or checkbox is clicked with the mouse, the mouse click event will fire with it's target object set to the radio button that was clicked. The radio button will also gain focus.

Both Internet Explorer and Firefox exhibit this behavior exactly (on true user clicks--we'll get to the event simulation methods shortly). Safari, however, only fires the click event. The checkbox or radio button that was clicked does not receive focus as it should.

So let's just always observe clicks and leave focus to the birds

I told you we'd get back to the event simulation methods in a minute. Both Firefox and Internet Explorer exhibit some strange behavior when using these methods vs. actual events. In Firefox, the click() method generates an event with the target set to the calling element--not the actual target of the click. This is inconsistent with both Firefox's focus() method and Internet Exlorer and Safari's handling of both the click() and focus() methods. This example (Firefox, Safari, and Opera compatible) demonstrates the issue.

So where does the problem start?

In the case when you need to force a particular radio button to be selected by default and you have additional Javascript logic that must run based on that selection. Let's say you have 4 radio buttons as in the previous example and you wish the 3rd radio button to be selected by default (we'll assume there's some Javascript logic that must happen based on the user's selection that must also occur with the default selection). Because the user will not be interacting with the default selection, we must rely on event methods to fire our events. So we have some challenges:

  • If we use click() and have our radio buttons listen for a click, Firefox will believe the target of the event is document. The radio button will be selected, but any additional logic based on knowing what was clicked (using event.target) will fail.
  • If we use focus() and have our radio buttons listen for focus, Safari will see the radio button receive focus correctly when the page loads as we will be using focus(). However, any actual user interaction will fail as the focus() event will not fire.

A workaround

I intend to open a bug in the Firefox bug tracker for this issue (if one is not already open; I didn't find one with a quick glance through Bugzilla). Until then, I've written a little workaround that requires the Prototype library to function.

First, ensure that your radio buttons are set up to respond to focus events (since we know that Firefox will only react properly to those events when called programmatically.

$('my-form').getInputs("radio").invoke('observe', 'focus', eventHandler);

Now, observe for clicks to forward on:

$('my-form').getInputs("radio").invoke('observe', 'click', fakeClick);

Your fakeClick method should look like this:

fakeClick: function(e){
   var el = e.element();
   if(el.identify) { /* Filter out click() for FireFox */
      if(this.focused.identify() != el.identify()) {
         e.element.focus(); /* Throws the proper focus() for Safari */
      }
   }
}

The other aspect of this is that within your actual event handler, you need to be sure to set the this.focused to the element that currently has focus.

I've created an example Prototype-enabled JS class to show how the functionality works.

Conclusion

So there you have it, some basic information about a bug in Firefox and a bug in Safari that together make for some interesting times when handling events; and a workaround which I hope you will find useful in getting around these two bugs. Please note that the code is more of an example on how to implement it; though it can be copied verbatim if you wish.

Download ClickFix.js (2kb)

Update 5/14/2009: By pure coincidence, I've added to this post exactly 1 year to the day after I first wrote it. Please see a new post on a Workaround for form submit events not firing with the submit method.