My dojo top ten (part 3: hitch)

I think I will call my series of posts dealing with dojo.query and NodeList part two of my dojo top ten and move on to part three.

I’ve come to rely heavily on dojo.hitch but at first I didn’t understand it at all. And I haven’t found many good explanations of it online (except this one) so I’m going to try my hand at a simple concise explanation of hitch.

Here we go: hitch returns a function in which ‘this’ will be whatever is specified as the first argument to hitch.

I’m now using it elsewhere but hitch is particularly useful with callback functions. So here’s an example:

dojo.xhrGet({
  url: 'http://mywebservice.com/helloworld',
  load: helloworldCallback

So we’re calling a webservice and specifying the callback function as helloworldCallback. This is all well and good but if you try to use ‘this’ in helloworldCallback, say to call other functions in the same module, it may not be what you expect it to be. Enter hitch:

dojo.xhrGet({
  url: 'http://mywebservice.com/helloworld',
  load: dojo.hitch(this, 'helloworldCallback')

By using hitch in the above example, we guarantee that when we hit the callback function, ‘this’ will refer to what we expect it to (in this case the module that contains both helloworldCallback and the function that does our webservice call).

Leave a Reply