5 Things to Know When Migrating Prototype to jQuery
Jan 02
work javascript, jquery, prototype 2 Comments
I just finished moving 1000+ lines of javascript from Prototype to jQuery. At first it went slow, but after a while it went relatively fast because the code was pretty basic. In the end, there were only 5 things that I needed to “translate”.
Prototype adds methods to the internal Javascript classes, while jQuery simply provides and a new function jQuery and a new type of object, the jQuery object, but otherwise Prototype and jQuery appear very similar. Both use the “$” in their syntax, but I prefer the alternate “jQuery” syntax below.
1. Selecting DOM elements
Prototype’s selector returns DOM elements.
$(element_id) => DOM element
jQuery does not.
jQuery('#'+element_id) => jQuery object which may include 0-n DOM elements.
jQuery('#'+element_id)[0] => first(and likely only) DOM element
The one gotcha is remembering when you’re dealing with a jQuery object or a DOM element.
2. Binding functions to contexts
Prototype has a bind function.
function.bind(context)
jQuery binds with a proxy.
jQuery.proxy(function, context)
3. Iterating over an array
Prototype adds an each method to Array.
Array.each(function(item){ ... })
jQuery can iterate over arrays.
jQuery.each(Array, function(item){ ... })
But usually you want to iterate over the results of a jQuery selector:
jQuery(".className").each(function(index, element){ ... })
4. Adding event handlers
Prototype adds the observe method to DOM elements
$(element_id).observe("click", function(event){ ... })
jQuery has the bind method.
jQuery('#'+element_id).bind("click", function(jQueryEvent){ ... })
…or the shorthand click (and others).
jQuery('#'+element_id).click(function(jQueryEvent){ ... })
The jQueryEvent object is not the same as a regular event object, but target() both work the same.
5. On DOM Ready
Initializing on DOM ready is done with Prototype’s observe method as:
document.observe("dom:loaded", function(){ ... })
In jQuery:
jQuery(function(){ ... })
I’m not a Prototype or jQuery expert, so your milage may vary. I’m mostly writing this for the next time I have to migrate Prototype to jQuery.