The pull was obvious, a lot of the smartest people in the Ruby community love jQuery. I couldn’t really get it, though. Chaining is cool, but its really just a parlor trick. What hooked me was the community. Just like Ruby (and unlike Prototype for the most part) jQuery has a thriving community of bloggers, plugin authors, and mailing lists. Part of jQuery is that is inherently extensible. Sure, prototype.js has Object.addMethods() but jQuery allows for easy packaging and distribution of new functionality. I’m sure I’m not the first one to say this, but its very true.
The one thing that kind of hung me up at first was how to organize my code. In Prototype, I used Class.create() a lot to encapsulate functionality for elements and areas of the site. Even using Class.create() with name-spacing like:
var MyApp = MyApp Feature = Class Create
I was kind of lost how to do this easily and effectively with jQuery. Do I create plugins for all of this functionality? I could, but that seemed messy to add to the global jQuery name-space when really what I wanted was an Object. John Resig to the rescue. 25 lines of code and now I have my Classes beautifully encapsulated. An interesting design pattern I happened upon with this, is using Class.extend() and jquery’s $.fn.data() to associate groups an instance of a Class with an element on-screen.
var Block = Class.extend this$element = $(); // ... // methods that can operate on an instance of block // and its elements. $().eachfunction $()data'block'this ;
This is instead of:
$fn.extend // a bunch of anonymous or private methods $()block;
The benefit of the Class way, is that now you always can just fetch and operate on the instance of Block for a particular element.
I need to dive a little deeper to see if there's a way to easily plugin-ize this pattern as I seem to be using it a bunch.
There are still a few small things I miss from Prototype, but for the most part either someone has ported them, or it pretty easy to do it yourself. For example, Function#bind():
// works like Prototype's Function#bind // in Prototype: // $('element').observe('click', this.clickMethod.bind(this)); // with jQuery + $.shove: // $('#element).click($.shove(this.clickMethod, this)); $.extend return function return fnapplyobject arguments; ;
Here are some great resources that I’ve found have made the whole switch lovely: