Tuesday, August 18, 2009

The zen of dojo.connect

One of the most used functions, yet least thought of in Dojo is dojo.connect.
Still, this small function is one of the best demonstrations of the power of the dynamical nature of Javascript.
Basically, what this function does is allow its users to call any function in any context, whenever a given function at a given scope was called.

Think of that last sentence again, up till now, if function T needed to be called due to the fact that function S was called, you had to follow the following steps:

1. Hope that the creator of function S provided a notification when function S was called

2. Hope that the creator of the object that holds function S provided an API that allows you to register to that notification, and made that option a public one.

Too much here relies on the API design capabilities of the creator of the function S.

Dojo solved it.

Dojo.connect is all about removing the need for relying on the good design skills of other people but you. Generally speaking this function takes function S, puts it aside and replaces it with a dispatcher, that calls all the T functions after that dispatcher first calls function S.

So where's the glorious dynamical nature of Javascript? function S is part of an object, let's call it O. Prior to calling dojo.connect, O.S was the function that was created by the author of the function S. After the call, O.S is another function, a function that dojo.connect injected there and this function does just I've described previously. Thus the API's of O are not harmed, but now there's no need for hoping whenever you use code that you are not responsible for and cannot be modified by you.