Naci
Naci

Reputation: 231

Understanding dojo hitch

I am struggling to understand hitch function of the dojo toolkit. I am looking at this example at https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html, which is the following:

require(["dojo/_base/lang"], function(lang){
var myObj = {
    foo: "bar",
    method: function(someArg){
      console.log(this.foo);
    }
  };

  var func = lang.hitch(myObj, "method");

  func();
});

Is it not possible to utilize that function by myObj.method(arg) instead? Thank you

Upvotes: 2

Views: 4281

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075337

Is it not possible to utilize that function by myObj.method(arg) instead?

Yes, it is in that particular case, but it's quite common to need to pass a function reference to other code, and function references don't (by default) carry any particular this baked into them; this gets set by how you call the function.

So for instance, if you use myObj.method as an event handler, when it gets called, this during the call won't refer to the object myObj refers to.

hitch fixes that by creating a new function that, when called, will call your method with this set correctly.

It's been dated for some time, ES5 (in 2009) introduced Function#bind, which does the same thing. But the Dojo Toolkit was initially created back in 2005, so it included utilities like this. Here's that same code using Function#bind instead:

require(["dojo/_base/lang"], function(lang){
  var myObj = {
    foo: "bar",
    method: function(someArg){
      console.log(this.foo);
    }
  };

  var func = myObj.method.bind(myObj);

  func();
});

Here's a live example demonstrating how it can matter in an event handler:

var obj = {
  foo: "bar",
  method: function() {
    console.log("this.foo = " + this.foo);
  }
};
document.getElementById("unbound").addEventListener("click", obj.method, false);
document.getElementById("bound").addEventListener("click", obj.method.bind(obj), false);
<input type="button" id="unbound" value="Unbound">
<input type="button" id="bound" value="Bound">

Upvotes: 6

Related Questions