Hacker News new | ask | show | jobs
by simonw 6581 days ago
I think they ended up having to do that because of jQuery's chaining support. Most of jQuery's functionality lives in a single namespace (jQuery.fn) which means you can chain method calls together like this:

jQuery('div:first').addClass('hello').text('Hello World').draggable().css('color', 'red');

If a plugin needs three or four methods, that's three or four extra functions on the one object - which ends up looking quite ugly:

jQuery('blah').draggable({options}).destroyDraggable()

The message passing idiom lets them add just one method to the jQuery.fn namespace that can cover a full range of different actions. I think it's a pretty clever pragmatic solution.

2 comments

I really like this DSL aspect of jQuery!

I wonder however if a plugin could define its own namespace, like:

    $('blah').draggable().create({options}).css(..)...
    $('blah').draggable().destroy().css(..)...
draggable() returns a wrapper that exposes only the dragging specific methods, but the underlying jQuery is passed through and returned by any method called on the wrapper. That way you don't have to add all methods in the same namespace.

On second thought I don't know if this wouldn't just be confusing :-)

I still don't like it in terms of taste. I guess one question would be how does it handle a typo in the string.

If you call a.destroooooy() then you'll get a js error, but if you call a.execute("destroooooy")...

They'll both be run-time errors, hopefully they throw an exception.